"
]
},
{
"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",
"
\n",
"\n",
"
\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",
"
\n",
"\n",
"
\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",
"
\n",
"\n",
"
\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",
"
\n",
"\n",
"
\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",
"
\n",
"\n",
"
"
]
},
{
"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": [
"
\n",
"\n",
"
\n",
"
\n",
"\n",
"
\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",
"
\n",
"\n",
"
\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": [
"
\n",
"\n",
"
\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": [
"
\n",
"\n",
"
\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": [
"
\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",
"
\n",
"\n",
"
\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": [
"
\n",
"\n",
"
\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
}