You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

1_exist_data_model.md 24 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. # 1: 使用已有模型在标准数据集上进行推理
  2. MMDetection 在 [Model Zoo](https://mmdetection.readthedocs.io/en/latest/model_zoo.html) 中提供了数以百计的检测模型,并支持多种标准数据集,包括 Pascal VOC,COCO,Cityscapes,LVIS 等。这份文档将会讲述如何使用这些模型和标准数据集来运行一些常见的任务,包括:
  3. - 使用现有模型在给定图片上进行推理
  4. - 在标准数据集上测试现有模型
  5. - 在标准数据集上训练预定义的模型
  6. ## 使用现有模型进行推理
  7. 推理是指使用训练好的模型来检测图像上的目标。在 MMDetection 中,一个模型被定义为一个配置文件和对应的存储在 checkpoint 文件内的模型参数的集合。
  8. 首先,我们建议从 [Faster RCNN](https://github.com/open-mmlab/mmdetection/tree/master/configs/faster_rcnn) 开始,其 [配置](https://github.com/open-mmlab/mmdetection/blob/master/configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py) 文件和 [checkpoint](http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth) 文件在此。
  9. 我们建议将 checkpoint 文件下载到 `checkpoints` 文件夹内。
  10. ### 推理的高层编程接口
  11. MMDetection 为在图片上推理提供了 Python 的高层编程接口。下面是建立模型和在图像或视频上进行推理的例子。
  12. ```python
  13. from mmdet.apis import init_detector, inference_detector
  14. import mmcv
  15. # 指定模型的配置文件和 checkpoint 文件路径
  16. config_file = 'configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py'
  17. checkpoint_file = 'checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth'
  18. # 根据配置文件和 checkpoint 文件构建模型
  19. model = init_detector(config_file, checkpoint_file, device='cuda:0')
  20. # 测试单张图片并展示结果
  21. img = 'test.jpg' # 或者 img = mmcv.imread(img),这样图片仅会被读一次
  22. result = inference_detector(model, img)
  23. # 在一个新的窗口中将结果可视化
  24. model.show_result(img, result)
  25. # 或者将可视化结果保存为图片
  26. model.show_result(img, result, out_file='result.jpg')
  27. # 测试视频并展示结果
  28. video = mmcv.VideoReader('video.mp4')
  29. for frame in video:
  30. result = inference_detector(model, frame)
  31. model.show_result(frame, result, wait_time=1)
  32. ```
  33. jupyter notebook 上的演示样例在 [demo/inference_demo.ipynb](https://github.com/open-mmlab/mmdetection/blob/master/demo/inference_demo.ipynb) 。
  34. ### 异步接口-支持 Python 3.7+
  35. 对于 Python 3.7+,MMDetection 也有异步接口。利用 CUDA 流,绑定 GPU 的推理代码不会阻塞 CPU,从而使得 CPU/GPU 在单线程应用中能达到更高的利用率。在推理流程中,不同数据样本的推理和不同模型的推理都能并发地运行。
  36. 您可以参考 `tests/async_benchmark.py` 来对比同步接口和异步接口的运行速度。
  37. ```python
  38. import asyncio
  39. import torch
  40. from mmdet.apis import init_detector, async_inference_detector
  41. from mmdet.utils.contextmanagers import concurrent
  42. async def main():
  43. config_file = 'configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py'
  44. checkpoint_file = 'checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth'
  45. device = 'cuda:0'
  46. model = init_detector(config_file, checkpoint=checkpoint_file, device=device)
  47. # 此队列用于并行推理多张图像
  48. streamqueue = asyncio.Queue()
  49. # 队列大小定义了并行的数量
  50. streamqueue_size = 3
  51. for _ in range(streamqueue_size):
  52. streamqueue.put_nowait(torch.cuda.Stream(device=device))
  53. # 测试单张图片并展示结果
  54. img = 'test.jpg' # or 或者 img = mmcv.imread(img),这样图片仅会被读一次
  55. async with concurrent(streamqueue):
  56. result = await async_inference_detector(model, img)
  57. # 在一个新的窗口中将结果可视化
  58. model.show_result(img, result)
  59. # 或者将可视化结果保存为图片
  60. model.show_result(img, result, out_file='result.jpg')
  61. asyncio.run(main())
  62. ```
  63. ### 演示样例
  64. 我们还提供了三个演示脚本,它们是使用高层编程接口实现的。 [源码在此](https://github.com/open-mmlab/mmdetection/tree/master/demo) 。
  65. #### 图片样例
  66. 这是在单张图片上进行推理的脚本,可以开启 `--async-test` 来进行异步推理。
  67. ```shell
  68. python demo/image_demo.py \
  69. ${IMAGE_FILE} \
  70. ${CONFIG_FILE} \
  71. ${CHECKPOINT_FILE} \
  72. [--device ${GPU_ID}] \
  73. [--score-thr ${SCORE_THR}] \
  74. [--async-test]
  75. ```
  76. 运行样例:
  77. ```shell
  78. python demo/image_demo.py demo/demo.jpg \
  79. configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
  80. checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
  81. --device cpu
  82. ```
  83. #### 摄像头样例
  84. 这是使用摄像头实时图片的推理脚本。
  85. ```shell
  86. python demo/webcam_demo.py \
  87. ${CONFIG_FILE} \
  88. ${CHECKPOINT_FILE} \
  89. [--device ${GPU_ID}] \
  90. [--camera-id ${CAMERA-ID}] \
  91. [--score-thr ${SCORE_THR}]
  92. ```
  93. 运行样例:
  94. ```shell
  95. python demo/webcam_demo.py \
  96. configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
  97. checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth
  98. ```
  99. #### 视频样例
  100. 这是在视频样例上进行推理的脚本。
  101. ```shell
  102. python demo/video_demo.py \
  103. ${VIDEO_FILE} \
  104. ${CONFIG_FILE} \
  105. ${CHECKPOINT_FILE} \
  106. [--device ${GPU_ID}] \
  107. [--score-thr ${SCORE_THR}] \
  108. [--out ${OUT_FILE}] \
  109. [--show] \
  110. [--wait-time ${WAIT_TIME}]
  111. ```
  112. 运行样例:
  113. ```shell
  114. python demo/video_demo.py demo/demo.mp4 \
  115. configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
  116. checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
  117. --out result.mp4
  118. ```
  119. ## 在标准数据集上测试现有模型
  120. 为了测试一个模型的精度,我们通常会在标准数据集上对其进行测试。MMDetection 支持多个公共数据集,包括 [COCO](https://cocodataset.org/) ,
  121. [Pascal VOC](http://host.robots.ox.ac.uk/pascal/VOC) ,[Cityscapes](https://www.cityscapes-dataset.com/) 等等。
  122. 这一部分将会介绍如何在支持的数据集上测试现有模型。
  123. ### 数据集准备
  124. 一些公共数据集,比如 Pascal VOC 及其镜像数据集,或者 COCO 等数据集都可以从官方网站或者镜像网站获取。
  125. 注意:在检测任务中,Pascal VOC 2012 是 Pascal VOC 2007 的无交集扩展,我们通常将两者一起使用。
  126. 我们建议将数据集下载,然后解压到项目外部的某个文件夹内,然后通过符号链接的方式,将数据集根目录链接到 `$MMDETECTION/data` 文件夹下,格式如下所示。
  127. 如果你的文件夹结构和下方不同的话,你需要在配置文件中改变对应的路径。
  128. ```plain
  129. mmdetection
  130. ├── mmdet
  131. ├── tools
  132. ├── configs
  133. ├── data
  134. │ ├── coco
  135. │ │ ├── annotations
  136. │ │ ├── train2017
  137. │ │ ├── val2017
  138. │ │ ├── test2017
  139. │ ├── cityscapes
  140. │ │ ├── annotations
  141. │ │ ├── leftImg8bit
  142. │ │ │ ├── train
  143. │ │ │ ├── val
  144. │ │ ├── gtFine
  145. │ │ │ ├── train
  146. │ │ │ ├── val
  147. │ ├── VOCdevkit
  148. │ │ ├── VOC2007
  149. │ │ ├── VOC2012
  150. ```
  151. 有些模型需要额外的 [COCO-stuff](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip) 数据集,比如 HTC,DetectoRS 和 SCNet,你可以下载并解压它们到 `coco` 文件夹下。文件夹会是如下结构:
  152. ```plain
  153. mmdetection
  154. ├── data
  155. │ ├── coco
  156. │ │ ├── annotations
  157. │ │ ├── train2017
  158. │ │ ├── val2017
  159. │ │ ├── test2017
  160. │ │ ├── stuffthingmaps
  161. ```
  162. PanopticFPN 等全景分割模型需要额外的 [COCO Panoptic](http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip) 数据集,你可以下载并解压它们到 `coco/annotations` 文件夹下。文件夹会是如下结构:
  163. ```text
  164. mmdetection
  165. ├── data
  166. │ ├── coco
  167. │ │ ├── annotations
  168. │ │ │ ├── panoptic_train2017.json
  169. │ │ │ ├── panoptic_train2017
  170. │ │ │ ├── panoptic_val2017.json
  171. │ │ │ ├── panoptic_val2017
  172. │ │ ├── train2017
  173. │ │ ├── val2017
  174. │ │ ├── test2017
  175. ```
  176. Cityscape 数据集的标注格式需要转换,以与 COCO 数据集标注格式保持一致,使用 `tools/dataset_converters/cityscapes.py` 来完成转换:
  177. ```shell
  178. pip install cityscapesscripts
  179. python tools/dataset_converters/cityscapes.py \
  180. ./data/cityscapes \
  181. --nproc 8 \
  182. --out-dir ./data/cityscapes/annotations
  183. ```
  184. ### 测试现有模型
  185. 我们提供了测试脚本,能够测试一个现有模型在所有数据集(COCO,Pascal VOC,Cityscapes 等)上的性能。我们支持在如下环境下测试:
  186. - 单 GPU 测试
  187. - 单节点多 GPU 测试
  188. - 多节点测试
  189. 根据以上测试环境,选择合适的脚本来执行测试过程。
  190. ```shell
  191. # 单 GPU 测试
  192. python tools/test.py \
  193. ${CONFIG_FILE} \
  194. ${CHECKPOINT_FILE} \
  195. [--out ${RESULT_FILE}] \
  196. [--eval ${EVAL_METRICS}] \
  197. [--show]
  198. # 单节点多 GPU 测试
  199. bash tools/dist_test.sh \
  200. ${CONFIG_FILE} \
  201. ${CHECKPOINT_FILE} \
  202. ${GPU_NUM} \
  203. [--out ${RESULT_FILE}] \
  204. [--eval ${EVAL_METRICS}]
  205. ```
  206. `tools/dist_test.sh` 也支持多节点测试,不过需要依赖 PyTorch 的 [启动工具](https://pytorch.org/docs/stable/distributed.html#launch-utility) 。
  207. 可选参数:
  208. - `RESULT_FILE`: 结果文件名称,需以 .pkl 形式存储。如果没有声明,则不将结果存储到文件。
  209. - `EVAL_METRICS`: 需要测试的度量指标。可选值是取决于数据集的,比如 `proposal_fast`,`proposal`,`bbox`,`segm` 是 COCO 数据集的可选值,`mAP`,`recall` 是 Pascal VOC 数据集的可选值。Cityscapes 数据集可以测试 `cityscapes` 和所有 COCO 数据集支持的度量指标。
  210. - `--show`: 如果开启,检测结果将被绘制在图像上,以一个新窗口的形式展示。它只适用于单 GPU 的测试,是用于调试和可视化的。请确保使用此功能时,你的 GUI 可以在环境中打开。否则,你可能会遇到这么一个错误 `cannot connect to X server`。
  211. - `--show-dir`: 如果指明,检测结果将会被绘制在图像上并保存到指定目录。它只适用于单 GPU 的测试,是用于调试和可视化的。即使你的环境中没有 GUI,这个选项也可使用。
  212. - `--show-score-thr`: 如果指明,得分低于此阈值的检测结果将会被移除。
  213. - `--cfg-options`: 如果指明,这里的键值对将会被合并到配置文件中。
  214. - `--eval-options`: 如果指明,这里的键值对将会作为字典参数被传入 `dataset.evaluation()` 函数中,仅在测试阶段使用。
  215. ### 样例
  216. 假设你已经下载了 checkpoint 文件到 `checkpoints/` 文件下了。
  217. 1. 测试 Faster R-CNN 并可视化其结果。按任意键继续下张图片的测试。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/master/configs/faster_rcnn) 。
  218. ```shell
  219. python tools/test.py \
  220. configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
  221. checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
  222. --show
  223. ```
  224. 2. 测试 Faster R-CNN,并为了之后的可视化保存绘制的图像。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/master/configs/faster_rcnn) 。
  225. ```shell
  226. python tools/test.py \
  227. configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
  228. checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
  229. --show-dir faster_rcnn_r50_fpn_1x_results
  230. ```
  231. 3. 在 Pascal VOC 数据集上测试 Faster R-CNN,不保存测试结果,测试 `mAP`。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/master/configs/pascal_voc) 。
  232. ```shell
  233. python tools/test.py \
  234. configs/pascal_voc/faster_rcnn_r50_fpn_1x_voc.py \
  235. checkpoints/faster_rcnn_r50_fpn_1x_voc0712_20200624-c9895d40.pth \
  236. --eval mAP
  237. ```
  238. 4. 使用 8 块 GPU 测试 Mask R-CNN,测试 `bbox` 和 `mAP` 。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/master/configs/mask_rcnn) 。
  239. ```shell
  240. ./tools/dist_test.sh \
  241. configs/mask_rcnn_r50_fpn_1x_coco.py \
  242. checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \
  243. 8 \
  244. --out results.pkl \
  245. --eval bbox segm
  246. ```
  247. 5. 使用 8 块 GPU 测试 Mask R-CNN,测试**每类**的 `bbox` 和 `mAP`。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/master/configs/mask_rcnn) 。
  248. ```shell
  249. ./tools/dist_test.sh \
  250. configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py \
  251. checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \
  252. 8 \
  253. --out results.pkl \
  254. --eval bbox segm \
  255. --options "classwise=True"
  256. ```
  257. 6. 在 COCO test-dev 数据集上,使用 8 块 GPU 测试 Mask R-CNN,并生成 JSON 文件提交到官方评测服务器。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/master/configs/mask_rcnn) 。
  258. ```shell
  259. ./tools/dist_test.sh \
  260. configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py \
  261. checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \
  262. 8 \
  263. --format-only \
  264. --options "jsonfile_prefix=./mask_rcnn_test-dev_results"
  265. ```
  266. 这行命令生成两个 JSON 文件 `mask_rcnn_test-dev_results.bbox.json` 和 `mask_rcnn_test-dev_results.segm.json`。
  267. 7. 在 Cityscapes 数据集上,使用 8 块 GPU 测试 Mask R-CNN,生成 txt 和 png 文件,并上传到官方评测服务器。配置文件和 checkpoint 文件 [在此](https://github.com/open-mmlab/mmdetection/tree/master/configs/cityscapes) 。
  268. ```shell
  269. ./tools/dist_test.sh \
  270. configs/cityscapes/mask_rcnn_r50_fpn_1x_cityscapes.py \
  271. checkpoints/mask_rcnn_r50_fpn_1x_cityscapes_20200227-afe51d5a.pth \
  272. 8 \
  273. --format-only \
  274. --options "txtfile_prefix=./mask_rcnn_cityscapes_test_results"
  275. ```
  276. 生成的 png 和 txt 文件在 `./mask_rcnn_cityscapes_test_results` 文件夹下。
  277. ### 不使用 Ground Truth 标注进行测试
  278. MMDetection 支持在不使用 ground-truth 标注的情况下对模型进行测试,这需要用到 `CocoDataset`。如果你的数据集格式不是 COCO 格式的,请将其转化成 COCO 格式。如果你的数据集格式是 VOC 或者 Cityscapes,你可以使用 [tools/dataset_converters](https://github.com/open-mmlab/mmdetection/tree/master/tools/dataset_converters) 内的脚本直接将其转化成 COCO 格式。如果是其他格式,可以使用 [images2coco 脚本](https://github.com/open-mmlab/mmdetection/tree/master/tools/dataset_converters/images2coco.py) 进行转换。
  279. ```shell
  280. python tools/dataset_converters/images2coco.py \
  281. ${IMG_PATH} \
  282. ${CLASSES} \
  283. ${OUT} \
  284. [--exclude-extensions]
  285. ```
  286. 参数:
  287. - `IMG_PATH`: 图片根路径。
  288. - `CLASSES`: 类列表文本文件名。文本中每一行存储一个类别。
  289. - `OUT`: 输出 json 文件名。 默认保存目录和 `IMG_PATH` 在同一级。
  290. - `exclude-extensions`: 待排除的文件后缀名。
  291. 在转换完成后,使用如下命令进行测试
  292. ```shell
  293. # 单 GPU 测试
  294. python tools/test.py \
  295. ${CONFIG_FILE} \
  296. ${CHECKPOINT_FILE} \
  297. --format-only \
  298. --options ${JSONFILE_PREFIX} \
  299. [--show]
  300. # 单节点多 GPU 测试
  301. bash tools/dist_test.sh \
  302. ${CONFIG_FILE} \
  303. ${CHECKPOINT_FILE} \
  304. ${GPU_NUM} \
  305. --format-only \
  306. --options ${JSONFILE_PREFIX} \
  307. [--show]
  308. ```
  309. 假设 [model zoo](https://mmdetection.readthedocs.io/en/latest/modelzoo_statistics.html) 中的 checkpoint 文件被下载到了 `checkpoints/` 文件夹下,
  310. 我们可以使用以下命令,用 8 块 GPU 在 COCO test-dev 数据集上测试 Mask R-CNN,并且生成 JSON 文件。
  311. ```sh
  312. ./tools/dist_test.sh \
  313. configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py \
  314. checkpoints/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth \
  315. 8 \
  316. -format-only \
  317. --options "jsonfile_prefix=./mask_rcnn_test-dev_results"
  318. ```
  319. 这行命令生成两个 JSON 文件 `mask_rcnn_test-dev_results.bbox.json` 和 `mask_rcnn_test-dev_results.segm.json`。
  320. ### 批量推理
  321. MMDetection 在测试模式下,既支持单张图片的推理,也支持对图像进行批量推理。默认情况下,我们使用单张图片的测试,你可以通过修改测试数据配置文件中的 `samples_per_gpu` 来开启批量测试。
  322. 开启批量推理的配置文件修改方法为:
  323. ```shell
  324. data = dict(train=dict(...), val=dict(...), test=dict(samples_per_gpu=2, ...))
  325. ```
  326. 或者你可以通过将 `--cfg-options` 设置为 `--cfg-options data.test.samples_per_gpu=2` 来开启它。
  327. ### 弃用 ImageToTensor
  328. 在测试模式下,弃用 `ImageToTensor` 流程,取而代之的是 `DefaultFormatBundle`。建议在你的测试数据流程的配置文件中手动替换它,如:
  329. ```python
  330. # (已弃用)使用 ImageToTensor
  331. pipelines = [
  332. dict(type='LoadImageFromFile'),
  333. dict(
  334. type='MultiScaleFlipAug',
  335. img_scale=(1333, 800),
  336. flip=False,
  337. transforms=[
  338. dict(type='Resize', keep_ratio=True),
  339. dict(type='RandomFlip'),
  340. dict(type='Normalize', mean=[0, 0, 0], std=[1, 1, 1]),
  341. dict(type='Pad', size_divisor=32),
  342. dict(type='ImageToTensor', keys=['img']),
  343. dict(type='Collect', keys=['img']),
  344. ])
  345. ]
  346. # (建议使用)手动将 ImageToTensor 替换为 DefaultFormatBundle
  347. pipelines = [
  348. dict(type='LoadImageFromFile'),
  349. dict(
  350. type='MultiScaleFlipAug',
  351. img_scale=(1333, 800),
  352. flip=False,
  353. transforms=[
  354. dict(type='Resize', keep_ratio=True),
  355. dict(type='RandomFlip'),
  356. dict(type='Normalize', mean=[0, 0, 0], std=[1, 1, 1]),
  357. dict(type='Pad', size_divisor=32),
  358. dict(type='DefaultFormatBundle'),
  359. dict(type='Collect', keys=['img']),
  360. ])
  361. ]
  362. ```
  363. ## 在标准数据集上训练预定义的模型
  364. MMDetection 也为训练检测模型提供了开盖即食的工具。本节将展示在标准数据集(比如 COCO)上如何训练一个预定义的模型。
  365. 重要信息:在配置文件中的学习率是在 8 块 GPU,每块 GPU 有 2 张图像(批大小为 8*2=16)的情况下设置的。
  366. 根据 [线性扩展规则](https://arxiv.org/abs/1706.02677) ,如果你使用不同数目的 GPU 或者每块 GPU 上有不同数量的图片,你需要设置学习率以正比于批大小,比如,
  367. 在 4 块 GPU 并且每张 GPU 上有 2 张图片的情况下,设置 `lr=0.01`; 在 16 块 GPU 并且每张 GPU 上有 4 张图片的情况下, 设置 `lr=0.08`。
  368. ### 数据集
  369. 训练需要准备好数据集,细节请参考 [数据集准备](#数据集准备) 。
  370. **注意**:
  371. 目前,`configs/cityscapes` 文件夹下的配置文件都是使用 COCO 预训练权值进行初始化的。如果网络连接不可用或者速度很慢,你可以提前下载现存的模型。否则可能在训练的开始会有错误发生。
  372. ### 使用单 GPU 训练
  373. 我们提供了 `tools/train.py` 来开启在单张 GPU 上的训练任务。基本使用如下:
  374. ```shell
  375. python tools/train.py \
  376. ${CONFIG_FILE} \
  377. [optional arguments]
  378. ```
  379. 在训练期间,日志文件和 checkpoint 文件将会被保存在工作目录下,它需要通过配置文件中的 `work_dir` 或者 CLI 参数中的 `--work-dir` 来指定。
  380. 默认情况下,模型将在每轮训练之后在 validation 集上进行测试,测试的频率可以通过设置配置文件来指定:
  381. ```python
  382. # 每 12 轮迭代进行一次测试评估
  383. evaluation = dict(interval=12)
  384. ```
  385. 这个工具接受以下参数:
  386. - `--no-validate` (**不建议**): 在训练期间关闭测试.
  387. - `--work-dir ${WORK_DIR}`: 覆盖工作目录.
  388. - `--resume-from ${CHECKPOINT_FILE}`: 从某个 checkpoint 文件继续训练.
  389. - `--options 'Key=value'`: 覆盖使用的配置文件中的其他设置.
  390. **注意**:
  391. `resume-from` 和 `load-from` 的区别:
  392. `resume-from` 既加载了模型的权重和优化器的状态,也会继承指定 checkpoint 的迭代次数,不会重新开始训练。`load-from` 则是只加载模型的权重,它的训练是从头开始的,经常被用于微调模型。
  393. ### 在多 GPU 上训练
  394. 我们提供了 `tools/dist_train.sh` 来开启在多 GPU 上的训练。基本使用如下:
  395. ```shell
  396. bash ./tools/dist_train.sh \
  397. ${CONFIG_FILE} \
  398. ${GPU_NUM} \
  399. [optional arguments]
  400. ```
  401. 可选参数和上一节所说的一致。
  402. #### 同时启动多个任务
  403. 如果你想在一台机器上启动多个任务的话,比如在一个有 8 块 GPU 的机器上启动 2 个需要 4 块GPU的任务,你需要给不同的训练任务指定不同的端口(默认为 29500)来避免冲突。
  404. 如果你使用 `dist_train.sh` 来启动训练任务,你可以使用命令来设置端口。
  405. ```shell
  406. CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4
  407. CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4
  408. ```
  409. #### 在多个节点上训练
  410. MMDetection 是依赖 `torch.distributed` 包进行分布式训练的。因此,我们可以通过 PyTorch 的 [启动工具](https://pytorch.org/docs/stable/distributed.html#launch-utility) 来进行基本地使用。
  411. #### 使用 Slurm 来管理任务
  412. Slurm 是一个常见的计算集群调度系统。在 Slurm 管理的集群上,你可以使用 `slurm.sh` 来开启训练任务。它既支持单节点训练也支持多节点训练。
  413. 基本使用如下:
  414. ```shell
  415. [GPUS=${GPUS}] ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR}
  416. ```
  417. 以下是在一个名称为 _dev_ 的 Slurm 分区上,使用 16 块 GPU 来训练 Mask R-CNN 的例子,并且将 `work-dir` 设置在了某些共享文件系统下。
  418. ```shell
  419. GPUS=16 ./tools/slurm_train.sh dev mask_r50_1x configs/mask_rcnn_r50_fpn_1x_coco.py /nfs/xxxx/mask_rcnn_r50_fpn_1x
  420. ```
  421. 你可以查看 [源码](https://github.com/open-mmlab/mmdetection/blob/master/tools/slurm_train.sh) 来检查全部的参数和环境变量.
  422. 在使用 Slurm 时,端口需要以下方的某个方法之一来设置。
  423. 1. 通过 `--options` 来设置端口。我们非常建议用这种方法,因为它无需改变原始的配置文件。
  424. ```shell
  425. CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR} --options 'dist_params.port=29500'
  426. CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR} --options 'dist_params.port=29501'
  427. ```
  428. 2. 修改配置文件来设置不同的交流端口。
  429. 在 `config1.py` 中,设置:
  430. ```python
  431. dist_params = dict(backend='nccl', port=29500)
  432. ```
  433. 在 `config2.py` 中,设置:
  434. ```python
  435. dist_params = dict(backend='nccl', port=29501)
  436. ```
  437. 然后你可以使用 `config1.py` 和 `config2.py` 来启动两个任务了。
  438. ```shell
  439. CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR}
  440. CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR}
  441. ```

No Description

Contributors (1)