{
  "cells": [
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "x7seefPduh36"
      },
      "source": [
        "<div align=\"center\">\n",
        "  <img width=\"600\" src=\"https://github.com/open-mmlab/mmyolo/raw/main/resources/mmyolo-logo.png\"/>\n",
        "  <div>&nbsp;</div>\n",
        "  <div align=\"center\">\n",
        "    <b><font size=\"5\">OpenMMLab website</font></b>\n",
        "    <sup>\n",
        "      <a href=\"https://openmmlab.com\">\n",
        "        <i><font size=\"4\">HOT</font></i>\n",
        "      </a>\n",
        "    </sup>\n",
        "    &nbsp;&nbsp;&nbsp;&nbsp;\n",
        "    <b><font size=\"5\">OpenMMLab platform</font></b>\n",
        "    <sup>\n",
        "      <a href=\"https://platform.openmmlab.com\">\n",
        "        <i><font size=\"4\">TRY IT OUT</font></i>\n",
        "      </a>\n",
        "    </sup>\n",
        "  </div>\n",
        "  <div>&nbsp;</div>\n",
        "\n",
        "<a href=\"https://colab.research.google.com/github/open-mmlab/mmyolo/blob/dev/demo/15_minutes_object_detection.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
        "\n",
        "[![PyPI](https://img.shields.io/pypi/v/mmyolo)](https://pypi.org/project/mmyolo)\n",
        "[![docs](https://img.shields.io/badge/docs-latest-blue)](https://mmyolo.readthedocs.io/en/latest/)\n",
        "[![deploy](https://github.com/open-mmlab/mmyolo/workflows/deploy/badge.svg)](https://github.com/open-mmlab/mmyolo/actions)\n",
        "[![codecov](https://codecov.io/gh/open-mmlab/mmyolo/branch/main/graph/badge.svg)](https://codecov.io/gh/open-mmlab/mmyolo)\n",
        "[![license](https://img.shields.io/github/license/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/blob/main/LICENSE)\n",
        "[![open issues](https://isitmaintained.com/badge/open/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/issues)\n",
        "[![issue resolution](https://isitmaintained.com/badge/resolution/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/issues)\n",
        "\n",
        "[📘Documentation](https://mmyolo.readthedocs.io/en/latest/) |\n",
        "[🛠️Installation](https://mmyolo.readthedocs.io/en/latest/get_started/installation.html) |\n",
        "[👀Model Zoo](https://mmyolo.readthedocs.io/en/latest/model_zoo.html) |\n",
        "[🆕Update News](https://mmyolo.readthedocs.io/en/latest/notes/changelog.html) |\n",
        "[🤔Reporting Issues](https://github.com/open-mmlab/mmyolo/issues/new/choose)\n",
        "\n",
        "</div>\n",
        "\n",
        "<div align=\"center\">\n",
        "  <a href=\"https://openmmlab.medium.com/\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/219255827-67c1a27f-f8c5-46a9-811d-5e57448c61d1.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://discord.com/channels/1037617289144569886/1046608014234370059\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/218347213-c080267f-cbb6-443e-8532-8e1ed9a58ea9.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://twitter.com/OpenMMLab\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/218346637-d30c8a0f-3eba-4699-8131-512fb06d46db.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://www.youtube.com/openmmlab\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/218346691-ceb2116a-465a-40af-8424-9f30d2348ca9.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://space.bilibili.com/1293512903\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/219026751-d7d14cce-a7c9-4e82-9942-8375fca65b99.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://www.zhihu.com/people/openmmlab\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/219026120-ba71e48b-6e94-4bd4-b4e9-b7d175b5e362.png\" width=\"3%\" alt=\"\" /></a>\n",
        "</div>"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "V6W8P5XEJGoc"
      },
      "source": [
        "# 15 minutes to get started with MMYOLO object detection\n",
        "\n",
        "Object detection task refers to that given a picture, the network predicts all the categories of objects included in the picture and the corresponding boundary boxes\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/220232979-fffa480b-9ae6-4601-8af6-4116265dc650.png\" alt=\"object detection\" width=\"800\"/>\n",
        "</div>\n",
        "\n",
        "Take the small dataset of cat as an example, you can easily learn MMYOLO object detection in 15 minutes. The whole process consists of the following steps:\n",
        "\n",
        "- [Installation](#installation)\n",
        "- [Dataset](#dataset)\n",
        "- [Config](#config)\n",
        "- [Training](#training)\n",
        "- [Testing](#testing)\n",
        "- [EasyDeploy](#easydeploy-deployment)\n",
        "\n",
        "In this tutorial, we take YOLOv5-s as an example. For the rest of the YOLO series algorithms, please see the corresponding algorithm configuration folder."
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "Ae5SqsA7wYGQ"
      },
      "source": [
        "## Installation\n",
        "\n",
        "Assuming you've already installed Conda in advance, then install PyTorch using the following commands."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XVLRaEIzwW-6",
        "outputId": "901b5db6-b1d7-4830-e746-485ee76d6648"
      },
      "outputs": [],
      "source": [
        "# -----------------------------------------------------------------------------------------\n",
        "# If you are using colab, you can skip this cell for PyTorch is pre-installed on the colab.\n",
        "# -----------------------------------------------------------------------------------------\n",
        "!python -V\n",
        "# Check nvcc version\n",
        "!nvcc -V\n",
        "# Check GCC version\n",
        "!gcc --version\n",
        "# Create a new Conda environment\n",
        "%conda create -n mmyolo python=3.8 -y\n",
        "%conda activate mmyolo\n",
        "# If you have GPU\n",
        "%conda install pytorch torchvision -c pytorch\n",
        "# If you only have CPU\n",
        "# %conda install pytorch torchvision cpuonly -c pytorch"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Check PyTorch version\n",
        "import torch\n",
        "print(torch.__version__)\n",
        "print(torch.cuda.is_available())"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Install MMYOLO and dependency libraries using the following commands.\n",
        "For details about how to configure the environment, see [Installation and verification](https://mmyolo.readthedocs.io/en/latest/get_started/installation.html).\n",
        "```{note}\n",
        "Note: Since this repo uses OpenMMLab 2.0, it is better to create a new conda virtual environment to prevent conflicts with the repo installed in OpenMMLab 1.0.\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "-qATUuntwmfD",
        "outputId": "24be577b-efce-46f2-8b2f-a65d02824467"
      },
      "outputs": [],
      "source": [
        "!git clone https://github.com/open-mmlab/mmyolo.git\n",
        "%cd mmyolo\n",
        "%pip install -U openmim\n",
        "!mim install -r requirements/mminstall.txt\n",
        "# Install albumentations\n",
        "!mim install -r requirements/albu.txt\n",
        "# Install MMYOLO\n",
        "!mim install -v -e .\n",
        "# \"-v\" means verbose, or more output\n",
        "# \"-e\" means installing a project in editable mode,\n",
        "# thus any local modifications made to the code will take effect without reinstallation."
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Dataset\n",
        "\n",
        "The Cat dataset is a single-category dataset consisting of 144 pictures (the original pictures are provided by @RangeKing, and cleaned by @PeterH0323), which contains the annotation information required for training. The sample image is shown below:\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/25873202/205423220-c4b8f2fd-22ba-4937-8e47-1b3f6a8facd8.png\" alt=\"cat dataset\"/>\n",
        "</div>\n",
        "\n",
        "You can download and use it directly by the following command:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "gMQXwWuIw3ef",
        "outputId": "c8efeac7-5b0c-4342-b5af-d3e790e358c3"
      },
      "outputs": [],
      "source": [
        "!python tools/misc/download_dataset.py --dataset-name cat --save-dir ./data/cat --unzip --delete"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "covQskXXw2ul"
      },
      "source": [
        "This dataset is automatically downloaded to the `./data/cat` dir with the following directory structure:\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/220072078-48b88a08-6179-483e-b8d3-0549e1b465de.png\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "The cat dataset is located in the mmyolo project dir, and `data/cat/annotations` stores annotations in COCO format, and `data/cat/images` stores all images\n",
        "\n",
        "## Config\n",
        "\n",
        "Taking YOLOv5 algorithm as an example, considering the limited GPU memory of users, we need to modify some default training parameters to make them run smoothly. The key parameters to be modified are as follows:\n",
        "\n",
        "- YOLOv5 is an Anchor-Based algorithm, and different datasets need to calculate suitable anchors adaptively\n",
        "- The default config uses 8 GPUs with a batch size of 16 per GPU. Now change it to a single GPU with a batch size of 12.\n",
        "- The default training epoch is 300. Change it to 40 epoch\n",
        "- Given the small size of the dataset, we opted to use fixed backbone weights\n",
        "- In principle, the learning rate should be linearly scaled accordingly when the batch size is changed, but actual measurements have found that this is not necessary\n",
        "\n",
        "Create a `yolov5_s-v61_fast_1xb12-40e_cat.py` config file in the `configs/yolov5` folder (we have provided this config for you to use directly) and copy the following into the config file.\n",
        "\n",
        "```python\n",
        "# Inherit and overwrite part of the config based on this config\n",
        "_base_ = 'yolov5_s-v61_syncbn_fast_8xb16-300e_coco.py'\n",
        "\n",
        "data_root = './data/cat/' # dataset root\n",
        "class_name = ('cat', ) # dataset category name\n",
        "num_classes = len(class_name) # dataset category number\n",
        "# metainfo is a configuration that must be passed to the dataloader, otherwise it is invalid\n",
        "# palette is a display color for category at visualization\n",
        "# The palette length must be greater than or equal to the length of the classes\n",
        "metainfo = dict(classes=class_name, palette=[(20, 220, 60)])\n",
        "\n",
        "# Adaptive anchor based on tools/analysis_tools/optimize_anchors.py\n",
        "anchors = [\n",
        "    [(68, 69), (154, 91), (143, 162)],  # P3/8\n",
        "    [(242, 160), (189, 287), (391, 207)],  # P4/16\n",
        "    [(353, 337), (539, 341), (443, 432)]  # P5/32\n",
        "]\n",
        "# Max training 40 epoch\n",
        "max_epochs = 40\n",
        "# bs = 12\n",
        "train_batch_size_per_gpu = 12\n",
        "# dataloader num workers\n",
        "train_num_workers = 4\n",
        "\n",
        "# load COCO pre-trained weight\n",
        "load_from = 'https://download.openmmlab.com/mmyolo/v0/yolov5/yolov5_s-v61_syncbn_fast_8xb16-300e_coco/yolov5_s-v61_syncbn_fast_8xb16-300e_coco_20220918_084700-86e02187.pth'  # noqa\n",
        "\n",
        "model = dict(\n",
        "    # Fixed the weight of the entire backbone without training\n",
        "    backbone=dict(frozen_stages=4),\n",
        "    bbox_head=dict(\n",
        "        head_module=dict(num_classes=num_classes),\n",
        "        prior_generator=dict(base_sizes=anchors)\n",
        "    ))\n",
        "\n",
        "train_dataloader = dict(\n",
        "    batch_size=train_batch_size_per_gpu,\n",
        "    num_workers=train_num_workers,\n",
        "    dataset=dict(\n",
        "        data_root=data_root,\n",
        "        metainfo=metainfo,\n",
        "        # Dataset annotation file of json path\n",
        "        ann_file='annotations/trainval.json',\n",
        "        # Dataset prefix\n",
        "        data_prefix=dict(img='images/')))\n",
        "\n",
        "val_dataloader = dict(\n",
        "    dataset=dict(\n",
        "        metainfo=metainfo,\n",
        "        data_root=data_root,\n",
        "        ann_file='annotations/test.json',\n",
        "        data_prefix=dict(img='images/')))\n",
        "\n",
        "test_dataloader = val_dataloader\n",
        "\n",
        "_base_.optim_wrapper.optimizer.batch_size_per_gpu = train_batch_size_per_gpu\n",
        "\n",
        "val_evaluator = dict(ann_file=data_root + 'annotations/test.json')\n",
        "test_evaluator = val_evaluator\n",
        "\n",
        "default_hooks = dict(\n",
        "    # Save weights every 10 epochs and a maximum of two weights can be saved.\n",
        "    # The best model is saved automatically during model evaluation\n",
        "    checkpoint=dict(interval=10, max_keep_ckpts=2, save_best='auto'),\n",
        "    # The warmup_mim_iter parameter is critical.\n",
        "    # The default value is 1000 which is not suitable for cat datasets.\n",
        "    param_scheduler=dict(max_epochs=max_epochs, warmup_mim_iter=10),\n",
        "    # The log printing interval is 5\n",
        "    logger=dict(type='LoggerHook', interval=5))\n",
        "# The evaluation interval is 10\n",
        "train_cfg = dict(max_epochs=max_epochs, val_interval=10)\n",
        "```\n",
        "\n",
        "The above config is inherited from `yolov5_s-v61_syncbn_fast_8xb16-300e_coco.py`. According to the characteristics of cat dataset updated `data_root`, `metainfo`, `train_dataloader`, `val_dataloader`, `num_classes` and other config.\n",
        "\n",
        "## Training"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python tools/train.py configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "TQ0h6sv_rJxq"
      },
      "source": [
        "Run the above training command, `work_dirs/yolov5_s-v61_fast_1xb12-40e_cat` folder will be automatically generated, the checkpoint file and the training config file will be saved in this folder. On a low-end 1660 GPU, the entire training process takes about eight minutes.\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/220236361-bd113606-248e-4a0e-a484-c0dc9e355b5b.png\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "The performance on `test.json` is as follows:\n",
        "\n",
        "```text\n",
        " Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.631\n",
        " Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.909\n",
        " Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.747\n",
        " Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = -1.000\n",
        " Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = -1.000\n",
        " Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.631\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.627\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.703\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.703\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = -1.000\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = -1.000\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.703\n",
        "```\n",
        "\n",
        "The above properties are printed via the COCO API, where -1 indicates that no object exists for the scale. According to the rules defined by COCO, the Cat dataset contains all large sized objects, and there are no small or medium-sized objects.\n",
        "\n",
        "### Some Notes\n",
        "\n",
        "Two key warnings are printed during training:\n",
        "\n",
        "- You are using `YOLOv5Head` with num_classes == 1. The loss_cls will be 0. This is a normal phenomenon.\n",
        "- The model and loaded state dict do not match exactly\n",
        "\n",
        "Neither of these warnings will have any impact on performance. The first warning is because the `num_classes` currently trained is 1, the loss of the classification branch is always 0 according to the community of the YOLOv5 algorithm, which is a normal phenomenon. The second warning is because we are currently training in fine-tuning mode, we load the COCO pre-trained weights for 80 classes,\n",
        "This will lead to the final Head module convolution channel number does not correspond, resulting in this part of the weight can not be loaded, which is also a normal phenomenon.\n",
        "\n",
        "### Training is resumed after the interruption\n",
        "\n",
        "If you stop training, you can add `--resume` to the end of the training command and the program will automatically resume training with the latest weights file from `work_dirs`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python tools/train.py configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py --resume"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "3sJxvQoUrMhX"
      },
      "source": [
        "### Save GPU memory strategy\n",
        "\n",
        "The above config requires about 3G RAM, so if you don't have enough, consider turning on mixed-precision training"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python tools/train.py configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py --amp"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "jVJdyHTxrQ9a"
      },
      "source": [
        "### Training visualization\n",
        "\n",
        "MMYOLO currently supports local, TensorBoard, WandB and other back-end visualization. The default is to use local visualization, and you can switch to WandB and other real-time visualization of various indicators in the training process.\n",
        "\n",
        "#### 1 WandB\n",
        "\n",
        "WandB visualization need registered in website, and in the https://wandb.ai/settings for wandb API Keys.\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://cdn.vansin.top/img/20220913212628.png\" alt=\"image\"/>\n",
        "</div>"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "%pip install wandb\n",
        "# After running wandb login, enter the API Keys obtained above, and the login is successful.\n",
        "!wandb login"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "Yu0_4YYRrbyY"
      },
      "source": [
        "Add the wandb config at the end of config file we just created: `configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py`.\n",
        "\n",
        "```python\n",
        "visualizer = dict(vis_backends = [dict(type='LocalVisBackend'), dict(type='WandbVisBackend')])\n",
        "```\n",
        "\n",
        "Running the training command and you will see the loss, learning rate, and coco/bbox_mAP visualizations in the link."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python tools/train.py configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "f_DyzfDIzwMa"
      },
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/222131114-30a79285-56bc-427d-a38d-8d6a6982ad60.png\" alt=\"image\"/>\n",
        "</div>\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/222132585-4b4962f1-211b-46f7-86b3-7534fc52a1b4.png\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "#### 2 Tensorboard\n",
        "\n",
        "Install Tensorboard using the following command."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "gHkGlii3n29Q"
      },
      "outputs": [],
      "source": [
        "%pip install tensorboard"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "bE-nx9TY1P-M"
      },
      "source": [
        "Add the `tensorboard` config at the end of config file we just created: `configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py`.\n",
        "\n",
        "```python\n",
        "visualizer = dict(vis_backends=[dict(type='LocalVisBackend'),dict(type='TensorboardVisBackend')])\n",
        "```\n",
        "\n",
        "After re-running the training command, Tensorboard file will be generated in the visualization folder `work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/{timestamp}/vis_data`.\n",
        "We can use Tensorboard to view the loss, learning rate, and coco/bbox_mAP visualizations from a web link by running the following command:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "g8fZgokho5CE"
      },
      "outputs": [],
      "source": [
        "!tensorboard --logdir=work_dirs/yolov5_s-v61_fast_1xb12-40e_cat"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "GUZ7MPoaro-o"
      },
      "source": [
        "## Testing"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VYmxtE0GunTB",
        "outputId": "f440807c-1931-4810-b76d-617f73fde227"
      },
      "outputs": [],
      "source": [
        "!python tools/test.py configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "                      work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
        "                      --show-dir show_results"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "_cFocUqN0BCb"
      },
      "source": [
        "Run the above test command, you can not only get the AP performance printed in the **Training** section, You can also automatically save the result images to the `work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/{timestamp}/show_results` folder. Below is one of the result images, the left image is the actual annotation, and the right image is the inference result of the model.\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/220251677-6c7e5c8f-9417-4803-97fc-a968d0172ab7.png\" alt=\"result_img\"/>\n",
        "</div>\n",
        "\n",
        "You can also visualize model inference results in a browser window if you use 'WandbVisBackend' or 'TensorboardVisBackend'.\n",
        "\n",
        "## Feature map visualization\n",
        "\n",
        "MMYOLO provides visualization scripts for feature map to analyze the current model training. Please refer to [Feature Map Visualization](../recommended_topics/visualization.md)\n",
        "\n",
        "Due to the bias of direct visualization of `test_pipeline`, we need modify the `test_pipeline` of `configs/yolov5/yolov5_s-v61_syncbn_8xb16-300e_coco.py`,\n",
        "\n",
        "```python\n",
        "test_pipeline = [\n",
        "    dict(\n",
        "        type='LoadImageFromFile',\n",
        "        file_client_args=_base_.file_client_args),\n",
        "    dict(type='YOLOv5KeepRatioResize', scale=img_scale),\n",
        "    dict(\n",
        "        type='LetterResize',\n",
        "        scale=img_scale,\n",
        "        allow_scale_up=False,\n",
        "        pad_val=dict(img=114)),\n",
        "    dict(type='LoadAnnotations', with_bbox=True, _scope_='mmdet'),\n",
        "    dict(\n",
        "        type='mmdet.PackDetInputs',\n",
        "        meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n",
        "                   'scale_factor', 'pad_param'))\n",
        "]\n",
        "```\n",
        "\n",
        "to the following config:\n",
        "\n",
        "```python\n",
        "test_pipeline = [\n",
        "    dict(\n",
        "        type='LoadImageFromFile',\n",
        "        file_client_args=_base_.file_client_args),\n",
        "    dict(type='mmdet.Resize', scale=img_scale, keep_ratio=False), # modify the LetterResize to mmdet.Resize\n",
        "    dict(type='LoadAnnotations', with_bbox=True, _scope_='mmdet'),\n",
        "    dict(\n",
        "        type='mmdet.PackDetInputs',\n",
        "        meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n",
        "                   'scale_factor'))\n",
        "]\n",
        "```\n",
        "\n",
        "Let's choose the `data/cat/images/IMG_20221020_112705.jpg` image as an example to visualize the output feature maps of YOLOv5 backbone and neck layers.\n",
        "\n",
        "**1. Visualize the three channels of YOLOv5 backbone**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python demo/featmap_vis_demo.py data/cat/images/IMG_20221020_112705.jpg \\\n",
        "                                 configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "                                 work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
        "                                 --target-layers backbone \\\n",
        "                                 --channel-reduction squeeze_mean"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/220292217-b343a6f4-0c88-4fdb-9680-35d0ff8e5bdb.png\" width=\"800\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "The result will be saved to the output folder in current path. Three output feature maps plotted in the above figure correspond to small, medium and large output feature maps. As the backbone of this training is not actually involved in training, it can be seen from the above figure that the big object cat is predicted on the small feature map, which is in line with the idea of hierarchical detection of object detection.\n",
        "\n",
        "**2. Visualize the three channels of YOLOv5 neck**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python demo/featmap_vis_demo.py data/cat/images/IMG_20221020_112705.jpg \\\n",
        "                                 configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "                                 work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
        "                                 --target-layers neck \\\n",
        "                                 --channel-reduction squeeze_mean"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/220293382-0a241415-e717-4688-a718-5f6d5c844785.png\" width=\"800\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "As can be seen from the above figure, because neck is involved in training, and we also reset anchor, the three output feature maps are forced to simulate the same scale object, resulting in the three output maps of neck are similar, which destroys the original pre-training distribution of backbone. At the same time, it can also be seen that 40 epochs are not enough to train the above dataset, and the feature maps do not perform well.\n",
        "\n",
        "**3. Grad-Based CAM visualization**\n",
        "\n",
        "Based on the above feature map visualization, we can analyze Grad CAM at the feature layer of bbox level.\n",
        "\n",
        "Install `grad-cam` package:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "%pip install \"grad-cam\""
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "(a) View Grad CAM of the minimum output feature map of the neck"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python demo/boxam_vis_demo.py data/cat/images/IMG_20221020_112705.jpg \\\n",
        "                                configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "                                work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
        "                                --target-layer neck.out_layers[2]"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "9v-dMkePvHMg"
      },
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/220298462-b0631f27-2366-4864-915a-a4ee21acd4b9.png\" width=\"800\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "(b) View Grad CAM of the medium output feature map of the neck"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "p9H9u0A-3KAD",
        "outputId": "32ca5a56-052f-4930-f53c-41cc3a9dc619"
      },
      "outputs": [],
      "source": [
        "!python demo/boxam_vis_demo.py data/cat/images/IMG_20221020_112705.jpg \\\n",
        "                               configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "                               work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
        "                               --target-layer neck.out_layers[1]"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "(c) View Grad CAM of the maximum output feature map of the neck"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "MrKan1U43uUY",
        "outputId": "690f8414-a76b-4fa6-e600-7cc874ce1914"
      },
      "outputs": [],
      "source": [
        "!python demo/boxam_vis_demo.py data/cat/images/IMG_20221020_112705.jpg \\\n",
        "                               configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "                               work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
        "                               --target-layer neck.out_layers[0]"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/220297905-e23369db-d383-48f9-b15e-528a70ec7b23.png\" width=\"800\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "## EasyDeploy deployment\n",
        "\n",
        "Here we'll use MMYOLO's [EasyDeploy](../../../projects/easydeploy/) to demonstrate the transformation deployment and basic inference of model.\n",
        "\n",
        "First you need to follow EasyDeploy's [basic documentation](../../../projects/easydeploy/docs/model_convert.md) controls own equipment installed for each library.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "%pip install onnx\n",
        "%pip install onnx-simplifier # Install if you want to use simplify\n",
        "%pip install tensorrt        # If you have GPU environment and need to output TensorRT model you need to continue execution"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Once installed, you can use the following command to transform and deploy the trained model on the cat dataset with one click. The current ONNX version is 1.13.0 and TensorRT version is 8.5.3.1, so keep the `--opset` value of 11. The remaining parameters need to be adjusted according to the config used. Here we export the CPU version of ONNX with the `--backend` set to 1."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 534
        },
        "id": "YsRFEecU5C0w",
        "outputId": "c26011d4-2836-4715-cd6b-68836294db33"
      },
      "outputs": [],
      "source": [
        "!python projects/easydeploy/tools/export.py \\\n",
        "\t    configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "\t    work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
        "\t    --work-dir work_dirs/yolov5_s-v61_fast_1xb12-40e_cat \\\n",
        "        --img-size 640 640 \\\n",
        "        --batch 1 \\\n",
        "        --device cpu \\\n",
        "        --simplify \\\n",
        "\t    --opset 11 \\\n",
        "\t    --backend 1 \\\n",
        "\t    --pre-topk 1000 \\\n",
        "\t    --keep-topk 100 \\\n",
        "\t    --iou-threshold 0.65 \\\n",
        "\t    --score-threshold 0.25\n"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "q1EY415x3Idx"
      },
      "source": [
        "On success, you will get the converted ONNX model under `work-dir`, which is named `end2end.onnx` by default.\n",
        "\n",
        "Let's use `end2end.onnx` model to perform a basic image inference:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python projects/easydeploy/tools/image-demo.py \\\n",
        "        data/cat/images/IMG_20210728_205312.jpg \\\n",
        "        configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "        work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/end2end.onnx \\\n",
        "        --device cpu"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "IrjiBa5YwDQM"
      },
      "source": [
        "After successful inference, the result image will be generated in the `output` folder of the default MMYOLO root directory. If you want to see the result without saving it, you can add `--show` to the end of the above command. For convenience, the following is the generated result.\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/7219519/221061210-b91e0b5b-652d-4dfc-8451-86a9a36f7d04.png\" width=\"800\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "Let's go on to convert the engine file for TensorRT, because TensorRT needs to be specific to the current environment and deployment version, so make sure to export the parameters, here we export the TensorRT8 file, the `--backend` is 2."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "d8zxczqiBLoB"
      },
      "outputs": [],
      "source": [
        "!python projects/easydeploy/tools/export.py \\\n",
        "        configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "        work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
        "        --work-dir work_dirs/yolov5_s-v61_fast_1xb12-40e_cat \\\n",
        "        --img-size 640 640 \\\n",
        "        --batch 1 \\\n",
        "        --device cuda:0 \\\n",
        "        --simplify \\\n",
        "        --opset 11 \\\n",
        "        --backend 2 \\\n",
        "        --pre-topk 1000 \\\n",
        "        --keep-topk 100 \\\n",
        "        --iou-threshold 0.65 \\\n",
        "        --score-threshold 0.25"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The resulting `end2end.onnx` is the ONNX file for the TensorRT8 deployment, which we will use to complete the TensorRT engine transformation."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "QFh8rIsX_kVw",
        "outputId": "c5bd6929-03a8-400e-be1e-581f32b23f61"
      },
      "outputs": [],
      "source": [
        "!python projects/easydeploy/tools/build_engine.py \\\n",
        "        work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/end2end.onnx \\\n",
        "        --img-size 640 640 \\\n",
        "        --device cuda:0"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Successful execution will generate the `end2end.engine` file under `work-dir`:\n",
        "\n",
        "```shell\n",
        "work_dirs/yolov5_s-v61_fast_1xb12-40e_cat\n",
        "├── 202302XX_XXXXXX\n",
        "│   ├── 202302XX_XXXXXX.log\n",
        "│   └── vis_data\n",
        "│       ├── 202302XX_XXXXXX.json\n",
        "│       ├── config.py\n",
        "│       └── scalars.json\n",
        "├── best_coco\n",
        "│   └── bbox_mAP_epoch_40.pth\n",
        "├── end2end.engine\n",
        "├── end2end.onnx\n",
        "├── epoch_30.pth\n",
        "├── epoch_40.pth\n",
        "├── last_checkpoint\n",
        "└── yolov5_s-v61_fast_1xb12-40e_cat.py\n",
        "```\n",
        "\n",
        "Let's continue use `image-demo.py` for image inference:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "rOqXEi-jAI7Y",
        "outputId": "2a21aaaa-d4ba-498a-f985-2a6a2b8d348f"
      },
      "outputs": [],
      "source": [
        "!python projects/easydeploy/tools/image-demo.py \\\n",
        "        data/cat/images/IMG_20210728_205312.jpg \\\n",
        "        configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
        "        work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/end2end.engine \\\n",
        "        --device cuda:0"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "ocHGUUEA_TjI"
      },
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/7219519/221061291-e7490bb6-5f0c-45ab-9fc4-caf2b62419d6.png\" width=\"800\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "This completes the transformation deployment of the trained model and checks the inference results. This is the end of the tutorial.\n",
        "\n",
        "If you encounter problems during training or testing, please check the [common troubleshooting steps](https://mmyolo.readthedocs.io/en/dev/recommended_topics/troubleshooting_steps.html) first and feel free to open an [issue](https://github.com/open-mmlab/mmyolo/issues/new/choose) if you still can't solve it.\n"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "gpuClass": "standard",
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
