手把手教你使用云服务器训练 RT-DETR (Pytorch版)
大家好,我是迪菲赫尔曼,这篇文章我将手把手带大家训练 RT-DETR
目标检测模型,
这篇教程是为刚入门同学准备的,如果你不会配置环境,又没有像样的算力,那我推荐大家严格跟着我的教程,很多坑我已经给大家通过代码补上了,跟着我的教程肯定能跑通。
我将采用 VSCode 远程连接 AutoDL 的方式进行本次教学, 代码采用 ultralytics
团队开源的 YOLOv8
项目进行训练,这个项目目前支持 RT-DETR
的训练验证和推理!
首先来说数据集, RT-DETR
的数据集格式是标准的 YOLO
格式的数据集,也就是一张图片对应一个标签,标签中有五个维度的信息,分别代表:物体的类别,物体框的中心点x坐标,中心点y坐标,框的宽,框的高。
虽然当我们训练时会默认下载一个数据集,但是为了让大家更清楚的了解这个过程,我又准备了一个处理好的YOLO
格式的数据集VOC2007
,关于怎么将数据集处理成 YOLO
格式,我不做太多的讲解,每个数据集格式都不一样,处理脚本也不会相同,并且大多数数据集都会包含YOLO
格式,拿过来直接用就可以。
数据集可以在我的资源里免费下载
如果我们按照标准的流程执行训练过程,我将过程总结为以下几步:
准备工作:
-
安装
VSCode
, Visual Studio Code - Code Editing. Redefined -
安装
VSCode
插件,Remote - SSH
、Chinese (Simplified)
-
注册
AudoDL
账号 , AutoDL算力云 -
上传数据集
-
租服务器
-
连接服务器
-
下载代码:
开启
AudoDL
学术资源加速:source /etc/network_turbo
下载代码:
https://github.com/ultralytics/ultralytics.git
解压数据集:
unzip -d /root/VOC/ VOC2007.zip
模型训练:
- 安装环境
pip install -r requirements.txt
。 新版用pip install -e .
- 测试环境
- 配置数据的
yaml
文件 - 训练模型
python rtdetr-train.py –epoch 10
- 查看指标
python rtdetr-val.py –task test
tensorboard
数据可视化tensorboard --logdir /root/ultralytics/runs/train
准备工作
1. 安装 VSCode
这一步并没有什么注意的点,我们打开 VSCode的官网,下载就好了
2. 安装 VSCode 插件
在这一步我们要在 VSCode
中,安装两个插件,分别是 Remote - SSH
和 Chinese (Simplified)
,
Remote - SSH
是我们做远程连接用的, Chinese (Simplified)
是将 VSCode
的汉化包,
VSCode
安装完成后就是如下页面,我们点击这个小方块的图标
分别在这里搜索并安装 Remote - SSH
和 Chinese (Simplified)
当左下角出现这个蓝色的logo
,说明我们的 Remote - SSH
就安装成功了。
至此 VSCode
的准备工作就结束了。
3. 注册 AudoDL 账号
AudoDL 的目标是为用户提供稳定可靠、价格公道的GPU算力,让GPU不再是您成为数据科学家道路上的拦路石。
这很适合自己实验室没有服务器的同学使用,这可以极大的简化我们的训练流程。
这也是目前大多数同学采用的方式,以下是部分显卡的租用价格。
4. 上传数据集
当我们进行操作时,依次点击以下步骤:首先点击“控制台”,然后选择“文件存储”,接着找到所需的区域(这里用“xx区”代替),最后点击“初始化文件存储”。
在这个过程中,有一点需要特别注意:在选择区域时,我们应该优先选择距离我们最近的区域。此外,一旦我们选择了特定区域并将数据集上传至该区域,我们之后租用显卡时也需要选择同一区域的显卡,否则将无法找到之前上传的数据集。这一点非常重要,务必记住!。这样才能确保我们顺利完成任务。
初始化完成后我们直接点击按钮上传就可以了:
5. 租服务器
计费方式:选择“按量计费”
选择地区:一定要选择你刚才上传数据集的地区
其它:按需选择就好
接下来是基础镜像选择,选择Pytorch
,框架版本2.0.0
,Python 3.8
,Cuda 11.8
,然后直接创建就行了。
RT-DETR 请务必选择这个版本的镜像,其它版本实测问题很多!
6. 连接服务器
当机器成功创建成功之后,我们可以在控制台看到如下的页面,
我们点击这个小方块去复制登录指令,并回到我们的 VSCode
,找到左下角的标志,
当出现这个页面说明我们安装成功了,
7. 下载代码
开启 AudoDL
学术资源加速:source /etc/network_turbo
下载代码:git clone https://github.com/ultralytics/ultralytics.git
解压数据集:unzip -d /root/VOC/ /root/autodl-fs/VOC2007
也就是我们直接在终端依次输入这三条指令,那么代码和数据集就都搞定了!
source /etc/network_turbo
git clone https://github.com/ultralytics/ultralytics.git
unzip -d /root/VOC/ /root/autodl-fs/VOC2007
模型训练
1. 安装环境
此时还要我们输入密码,我们复制就可以了。
当出现这个页面,我们就可以准备安装环境了。
这一步只要你在终端中输入以下的指令,除此之外什么都不用装!
pip install -r requirements.txt
出现这个说明安装成功,警告可以忽略掉
2. 测试环境
大家直接运行我的代码,如果可以检测出目标,说明环境安装成功,
其实这步是完全可以跳过的,按照我给的方法安装环境绝对不会出错的。
import sys
sys.path.append("/root/ultralytics")
from ultralytics import RTDETR
if __name__ == '__main__':
# Load a COCO-pretrained RT-DETR-l model
model = RTDETR('rtdetr-l.pt')
model.predict(
source= r'/root/ultralytics/ultralytics/assets/bus.jpg',
save=True, # save predict results
imgsz=640, # (int) size of input images as integer or w,h
conf=0.25, # object confidence threshold for detection (default 0.25 predict, 0.001 val)
iou=0.45, # # intersection over union (IoU) threshold for NMS
show=False, # show results if possible
project='runs/predict', # (str, optional) project name
name='exp', # (str, optional) experiment name, results saved to 'project/name' directory
save_txt=False, # save results as .txt file
save_conf=True, # save results with confidence scores
save_crop=False, # save cropped images with results
show_labels=True, # show object labels in plots
show_conf=True, # show object confidence scores in plots
vid_stride=1, # video frame-rate stride
line_width=3, # bounding box thickness (pixels)
visualize=False, # visualize model features
augment=False, # apply image augmentation to prediction sources
agnostic_nms=False, # class-agnostic NMS
retina_masks=False, # use high-resolution segmentation masks
boxes=True, # Show boxes in segmentation predictions
)
3. 配置数据集 yaml 文件
首先在 ultralytics/cfg/datasets/
下新建一个 my-data.yaml
文件,
内容可以直接复制我下面的,
path: ../VOC
train: # train images
- images/train
val: # val images
- images/val
test: # test images
- images/test
# Classes
names:
0: aeroplane
1: bicycle
2: bird
3: boat
4: bottle
5: bus
6: car
7: cat
8: chair
9: cow
10: diningtable
11: dog
12: horse
13: motorbike
14: person
15: pottedplant
16: sheep
17: sofa
18: train
19: tvmonitor
4. 模型训练
训练要求我们在 ultralytics
下新建一个 python
文件,我这里叫 rt-detr-train.py
,内容可以复制我的,我已经对超参数进行了调整,
本次训练我使用了预训练权重,并且训练了
72
72
72 个epoch
import sys
sys.path.append("/root/ultralytics")
from ultralytics import RTDETR
if __name__ == '__main__':
# Load a COCO-pretrained RT-DETR-l model
model = RTDETR('rtdetr-l.pt')
# Train the model on the COCO8 example dataset for 100 epochs
model.train(
data='ultralytics/cfg/datasets/my-data.yaml',
epochs=72,
imgsz=640,
batch=16,
patience= 50 , # (int) epochs to wait for no observable improvement for early stopping of training
save= True , # (bool) save train checkpoints and predict results
save_period= -1, # (int) Save checkpoint every x epochs (disabled if < 1)
cache= False , # (bool) True/ram, disk or False. Use cache for data loading
device='' , # (int | str | list, optional) device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu
workers= 8 , # (int) number of worker threads for data loading (per RANK if DDP)
project= 'runs/train', # (str, optional) project name
name= 'exp' ,# (str, optional) experiment name, results saved to 'project/name' directory
exist_ok= False , # (bool) whether to overwrite existing experiment
pretrained= True , # (bool | str) whether to use a pretrained model (bool) or a model to load weights from (str)
optimizer= 'Adam', # (str) optimizer to use, choices=[SGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp, auto]
verbose= True ,# (bool) whether to print verbose output
seed= 0 , # (int) random seed for reproducibility
deterministic= True , # (bool) whether to enable deterministic mode
single_cls= False , # (bool) train multi-class data as single-class
rect= False ,# (bool) rectangular training if mode='train' or rectangular validation if mode='val'
cos_lr= True , # (bool) use cosine learning rate scheduler
close_mosaic= 0, # (int) disable mosaic augmentation for final epochs
resume= False , # (bool) resume training from last checkpoint
amp= True, # (bool) Automatic Mixed Precision (AMP) training, choices=[True, False], True runs AMP check
fraction= 1.0 , # (float) dataset fraction to train on (default is 1.0, all images in train set)
profile= False, # (bool) profile ONNX and TensorRT speeds during training for loggers
# Hyperparameters ----------------------------------------------------------------------------------------------
lr0=0.0001, # (float) initial learning rate (i.e. SGD=1E-2, Adam=1E-3)
lrf=0.0001, # (float) final learning rate (lr0 * lrf)
momentum=0.937, # (float) SGD momentum/Adam beta1
weight_decay=0.0001, # (float) optimizer weight decay 5e-4
warmup_epochs=5.0, # (float) warmup epochs (fractions ok)
warmup_momentum=0.8, # (float) warmup initial momentum
warmup_bias_lr=0.1, # (float) warmup initial bias lr
pose=12.0, # (float) pose loss gain
kobj=1.0, # (float) keypoint obj loss gain
label_smoothing=0.0, # (float) label smoothing (fraction)
nbs=64, # (int) nominal batch size
hsv_h=0.015, # (float) image HSV-Hue augmentation (fraction)
hsv_s=0.7, # (float) image HSV-Saturation augmentation (fraction)
hsv_v=0.4, # (float) image HSV-Value augmentation (fraction)
degrees=0.0, # (float) image rotation (+/- deg)
translate=0.1, # (float) image translation (+/- fraction)
scale=0.5, # (float) image scale (+/- gain)
shear=0.0, # (float) image shear (+/- deg)
perspective=0.0, # (float) image perspective (+/- fraction), range 0-0.001
flipud=0.0, # (float) image flip up-down (probability)
fliplr=0.5, # (float) image flip left-right (probability)
mosaic=0.0, # (float) image mosaic (probability)
mixup=0.0, # (float) image mixup (probability)
copy_paste=0.0, # (float) segment copy-paste (probability)
)
开始训练时,要下载 yolov8n.pt
文件,虽然我们没用到,但是这是必须下载的,
当模型训练完成后,会显示如下信息,里面有模型的训练时间和各类别的指标信息。
在上图提示的路径下我们可以找到我们最终得到的文件:
文件夹包含的东西有很多,我们可以根据文件名判断内容。
5. 查看指标
在第4部分打印出的指标是验证集的指标,验证集是给我们调整超参数用的,由于我已经进行了超参数调整,
所以下面我们要查看测试集的指标,最终将测试集指标写在论文里。
这里我依然给大家写一个文件,使用我给的这个文件可以方便大家调整各种参数,
我这里叫 rt-detr-val.py
import sys
sys.path.append("/root/ultralytics")
from ultralytics import RTDETR
if __name__ == '__main__':
# Load a model
model = RTDETR('runs/train/exp/weights/best.pt') #
# Validate the model
model.val(
val=True, # (bool) validate/test during training
data=r'ultralytics/cfg/datasets/my-data.yaml',
split='test', # (str) dataset split to use for validation, i.e. 'val', 'test' or 'train'
batch=1, # (int) number of images per batch (-1 for AutoBatch)
imgsz=640, # (int) size of input images as integer or w,h
device='', # (int | str | list, optional) device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu
workers=8, # (int) number of worker threads for data loading (per RANK if DDP)
save_json=False, # (bool) save results to JSON file
save_hybrid=False, # (bool) save hybrid version of labels (labels + additional predictions)
conf=0.001, # (float, optional) object confidence threshold for detection (default 0.25 predict, 0.001 val)
iou=0.6, # (float) intersection over union (IoU) threshold for NMS
project='runs/val', # (str, optional) project name
name='exp', # (str, optional) experiment name, results saved to 'project/name' directory
max_det=300, # (int) maximum number of detections per image
half=False, # (bool) use half precision (FP16)
dnn=False, # (bool) use OpenCV DNN for ONNX inference
plots=True, # (bool) save plots during train/val
)
红色框中显示的就是模型的推理速度,我们使用 1000 / ( 0.1 + 7.9 + 0.0 + 0.2 ) = 121.95122 1000/(0.1+7.9+0.0+0.2)=121.95122 1000/(0.1+7.9+0.0+0.2)=121.95122
这个 100 100 100 就是最终模型的 FPS,但是这个值误差挺大的,大家多测几次。
6. 模型推理 & 数据可视化
使用自己训练的模型推理,大家依然可以参考我的代码,下面放上我刚刚训练好的模型的检测效果。
我这里叫 rt-detr-detect.py
import sys
sys.path.append("/root/ultralytics")
from ultralytics import RTDETR
if __name__ == '__main__':
# Load a COCO-pretrained RT-DETR-l model
model = RTDETR('runs/train/exp/weights/best.pt')
model.predict(
source= r'/root/ultralytics/ultralytics/assets/bus.jpg',
save=True, # save predict results
imgsz=640, # (int) size of input images as integer or w,h
conf=0.25, # object confidence threshold for detection (default 0.25 predict, 0.001 val)
iou=0.45, # # intersection over union (IoU) threshold for NMS
show=False, # show results if possible
project='runs/predict', # (str, optional) project name
name='exp', # (str, optional) experiment name, results saved to 'project/name' directory
save_txt=False, # save results as .txt file
save_conf=True, # save results with confidence scores
save_crop=False, # save cropped images with results
show_labels=True, # show object labels in plots
show_conf=True, # show object confidence scores in plots
vid_stride=1, # video frame-rate stride
line_width=3, # bounding box thickness (pixels)
visualize=False, # visualize model features
augment=False, # apply image augmentation to prediction sources
agnostic_nms=False, # class-agnostic NMS
retina_masks=False, # use high-resolution segmentation masks
boxes=True, # Show boxes in segmentation predictions
)
通过下面的指令就可以通过 tensorboard
查看可视化结果。
tensorboard --logdir /root/ultralytics/runs/train
常见问题
问题1:
/root/miniconda3/lib/python3.8/site-packages/torch/autograd/init.py:200: UserWarning: grid_sampler_2d_backward_cuda does not have a deterministic implementation, but you set ‘torch.use_deterministic_algorithms(True, warn_only=True)’. You can file an issue at https://github.com/pytorch/pytorch/issues to help us prioritize adding deterministic support for this operation. (Triggered internally at …/aten/src/ATen/Context.cpp:71.)
Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
解决方法:
在你的代码中找到设置 torch.use_deterministic_algorithms(True, warn_only=True)的地方,将其改为torch.use_deterministic_algorithms(False, warn_only=True)。
torch.use_deterministic_algorithms(False, warn_only=True)