尧图精选

MMDetection 配置迁移完全指南:从 2.x 迁移到 3.x 的字段对照、实操示例与源码解析

🕒 发布时间:2026/9/20 0:21:19 📁 来源:尧图网络
MMDetection 配置迁移完全指南从 2.x 迁移到 3.x 的字段对照、实操示例与源码解析【免费下载链接】mmdetectionOpenMMLab Detection Toolbox and Benchmark项目地址: https://gitcode.com/gh_mirrors/mm/mmdetection导读MMDetection 3.x 基于 MMEngine 重构了整套配置体系data、optimizer、lr_config、runner、evaluation等 2.x 时代的顶层字段被全面拆分与重组。本文以官方迁移文档为主体以 Mask R-CNN 的配置文件为贯穿全篇的实例逐项对照 2.x 与 3.x 的配置写法覆盖模型配置DataPreprocessor、数据集与评测器Dataloader/Dataset/Evaluator、数据变换流水线Pipeline、训练测试循环、优化配置optim_wrapper / param_scheduler、Hook 与运行时配置并结合当前仓库的源码实现给出底层原理佐证。读完本文你将能独立把任意 2.x 配置文件完整、正确地迁移到 3.x并理解每个迁移点背后的设计动机。本文依据的官方迁移文档位于 docs/en/migration/config_migration.md与它配套的基础概念请先阅读 Learn about Configs下文简称《配置教程》。迁移总览3.x 配置体系的三个设计转变在进入逐字段对照之前先把握 3.x 配置体系的三条主线后续所有迁移点都由它们派生数据处理职责上移图像归一化Normalize与填充Pad从数据流水线pipeline中移出统一收进model.data_preprocessor这一新模块在 batch 层面统一完成加载到显存 → 归一化 → 填充 → BGR/RGB 转换。配置字段按运行阶段拆分2.x 用一个data字段同时描述训练/验证/测试用evaluation字段描述评测3.x 将训练、验证、测试的加载配置分别拆到train_dataloader/val_dataloader/test_dataloader评测拆到val_evaluator/test_evaluator训练与推理循环拆到train_cfg/val_cfg/test_cfg。底层引擎全面切换到 MMEngine训练循环、Hook、日志、可视化、优化器包装、学习率调度等均改为 MMEngine 的 Runner / Hook / optim_wrapper / param_scheduler 体系因此配置风格与 PyTorch 官方 API 更为贴近。从仓库结构看configs/_base_/下目前维护着models/、datasets/、schedules/、default_runtime.py四类基础配置见 configs/base/任何算法配置都通过_base_继承组合而成例如 configs/mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py 只写了四行_base_引用其余全部来自基础配置。一、模型配置迁移DataPreprocessor 取代 Normalize Pad1.1 迁移结论模型主体不变新增 data_preprocessor2.x 迁移到 3.x 时模型配置的backbone、neck、各head、train_cfg、test_cfg等字段几乎无需改动参数保持与 2.x 一致。例如 configs/base/models/mask-rcnn_r50_fpn.py 中backboneResNet-50、neckFPN、rpn_head、roi_head的结构与 2.x 完全同构。3.x 真正新增的是model.data_preprocessor字段它替代了 2.x 中 pipeline 末尾的Normalize与Pad两个变换。官方给出的 2.x 与 3.x 对照如下2.x 配置归一化与填充在 pipeline 中# Image normalization parameters img_norm_cfg dict( mean[123.675, 116.28, 103.53], std[58.395, 57.12, 57.375], to_rgbTrue) pipeline[ ..., dict(typeNormalize, **img_norm_cfg), dict(typePad, size_divisor32), # Padding the image to multiples of 32 ... ]3.x 配置归一化与填充在 data_preprocessor 中model dict( data_preprocessordict( typeDetDataPreprocessor, # Image normalization parameters mean[123.675, 116.28, 103.53], std[58.395, 57.12, 57.375], bgr_to_rgbTrue, # Image padding parameters pad_maskTrue, # In instance segmentation, the mask needs to be padded pad_size_divisor32) # Padding the image to multiples of 32 )1.2 源码视角DetDataPreprocessor 究竟做了什么DetDataPreprocessor的实现在 mmdet/models/data_preprocessors/data_preprocessor.py它继承自 MMEngine 的ImgDataPreprocessor。从其类文档与构造函数L30-L108可以看到它负责Collate 并搬运数据到目标设备把 dataloader 产出的 batch 搬到 GPUVRAM归一化用配置的mean/std对图像像素做标准化填充将 batch 内图像填充到当前 batch 最大尺寸且填充后的尺寸可被pad_size_divisor整除通道顺序转换bgr_to_rgbTrue时把输入从 BGR 转成 RGB对应 2.xNormalize里的to_rgbTrue实例分割专属选项pad_maskTrue时对实例掩码同步填充2.x 的Pad只处理图像3.x 需要显式声明掩码是否需要填充同类参数还有mask_pad_value掩码填充值默认 0、pad_seg/seg_pad_value语义分割图填充默认值 255见 L81-L90训练期 batch 增强支持batch_augments参数挂载 BatchAugment如 BatchSyncRandomResize、Mosaic 等这也是 2.x 不具备的能力L99-L103。参数默认值在源码中有明确定义pad_size_divisor1、pad_value0、bgr_to_rgbFalse、pad_maskFalse、boxtype2tensorTrue、non_blockingFalseL77-L90。因此迁移时若你的 2.x 配置只有归一化而没有按 32 对齐填充3.x 中pad_size_divisor应保持默认 1 或按需显式设置。二、数据集与评测器配置迁移这是 2.x 到 3.x 改动最大的部分官方文档从三个维度展开Dataloader 与 Dataset、数据变换 Pipeline、Evaluator 配置。2.1 Dataloader 与 Dataset从 data 字段到三个独立 dataloader2.x 中训练/验证/测试的数据加载设置统一放在data字段下且samples_per_gpu、workers_per_gpu直接写死。3.x 的train_dataloader/val_dataloader/test_dataloader参数与PyTorch 官方 DataLoader 对齐并且把 2.x 中不可配置的sampler、batch_sampler、persistent_workers也开放到了配置文件中。官方对照如下2.x 配置data dict( samples_per_gpu2, workers_per_gpu2, traindict( typedataset_type, ann_filedata_root annotations/instances_train2017.json, img_prefixdata_root train2017/, pipelinetrain_pipeline), valdict( typedataset_type, ann_filedata_root annotations/instances_val2017.json, img_prefixdata_root val2017/, pipelinetest_pipeline), testdict( typedataset_type, ann_filedata_root annotations/instances_val2017.json, img_prefixdata_root val2017/, pipelinetest_pipeline))3.x 配置train_dataloader dict( batch_size2, num_workers2, persistent_workersTrue, # Avoid recreating subprocesses after each iteration samplerdict(typeDefaultSampler, shuffleTrue), # Default sampler, supports both distributed and non-distributed training batch_samplerdict(typeAspectRatioBatchSampler), # Default batch_sampler, used to ensure that images in the batch have similar aspect ratios, so as to better utilize graphics memory datasetdict( typedataset_type, data_rootdata_root, ann_fileannotations/instances_train2017.json, data_prefixdict(imgtrain2017/), filter_cfgdict(filter_empty_gtTrue, min_size32), pipelinetrain_pipeline)) # In version 3.x, validation and test dataloaders can be configured independently val_dataloader dict( batch_size1, num_workers2, persistent_workersTrue, drop_lastFalse, samplerdict(typeDefaultSampler, shuffleFalse), datasetdict( typedataset_type, data_rootdata_root, ann_fileannotations/instances_val2017.json, data_prefixdict(imgval2017/), test_modeTrue, pipelinetest_pipeline)) test_dataloader val_dataloader # The configuration of the testing dataloader is the same as that of the validation dataloader, which is omitted here迁移要点逐条说明samples_per_gpu→batch_size语义完全对应指单卡 batch size。workers_per_gpu→num_workers对应 PyTorch DataLoader 的num_workers。data.train / data.val / data.test→train_dataloader.dataset / val_dataloader.dataset / test_dataloader.dataset数据集本身的配置被嵌套进各 dataloader 的dataset子字段。img_prefix→data_prefixdict(img...)2.x 用字符串拼接路径3.x 用data_prefix字典支持多模态数据分别声明img、seg、pan_seg等前缀。新增filter_cfgfilter_empty_gtTrue, min_size32表示过滤掉没有 GT 的图片以及小尺寸宽或高小于 32目标这是 2.x 中LoadAnnotations内部隐式完成、3.x 显式化的配置。新增sampler与batch_samplerDefaultSampler同时支持分布式与非分布式训练AspectRatioBatchSampler将宽高比相近的图片分到同一 batch提升显存利用率这也是 2.x 内部固定的行为3.x 开放出来可配置。test_modeTrue验证/测试时关闭数据集内部的 GT 过滤与数据增强相关逻辑。persistent_workersTrue每个 epoch 结束后不销毁 worker 子进程避免反复创建进程能加速训练验证/测试时通常搭配drop_lastFalse避免因 batch size 无法整除而丢弃最后一批样本。这一结构在仓库中的真实样板可见 configs/base/datasets/coco_instance.pyL37-L65训练 batch_size2、验证 batch_size1官方注释明确提醒验证时 batch 大于 1 会产生额外 padding 区域可能影响评测精度test_dataloader val_dataloader直接复用。2.2 数据变换 Pipeline去掉 Normalize/PadCollect 与 DefaultFormatBundle 合并为 PackDetInputs由于归一化与填充已上移到data_preprocessor3.x 的train_pipeline中不再需要Normalize和Pad同时 2.x 中负责收集指定键的Collect与统一格式打包的DefaultFormatBundle被合并为新的PackDetInputs。PackDetInputs负责把流水线产出的数据打包成模型的输入格式更详细的输入格式流转见 数据流文档。2.x 的 Mask R-CNN train_pipelineimg_norm_cfg dict( mean[123.675, 116.28, 103.53], std[58.395, 57.12, 57.375], to_rgbTrue) train_pipeline [ dict(typeLoadImageFromFile), dict(typeLoadAnnotations, with_bboxTrue), dict(typeResize, img_scale(1333, 800), keep_ratioTrue), dict(typeRandomFlip, flip_ratio0.5), dict(typeNormalize, **img_norm_cfg), dict(typePad, size_divisor32), dict(typeDefaultFormatBundle), dict(typeCollect, keys[img, gt_bboxes, gt_labels]), ]3.x 的 Mask R-CNN train_pipelinetrain_pipeline [ dict(typeLoadImageFromFile), dict(typeLoadAnnotations, with_bboxTrue), dict(typeResize, scale(1333, 800), keep_ratioTrue), dict(typeRandomFlip, prob0.5), dict(typePackDetInputs) ]可见流水线从 8 步缩短为 5 步结构更清爽。test_pipeline 的迁移同样移除Normalize和Pad除此之外还有一个重要变化TTA测试时增强从普通测试流程中剥离2.x 的MultiScaleFlipAug被移除TTA 改为通过独立配置实现详见 TTA 文档。2.x 的 Mask R-CNN test_pipelinetest_pipeline [ dict(typeLoadImageFromFile), dict( typeMultiScaleFlipAug, img_scale(1333, 800), flipFalse, transforms[ dict(typeResize, keep_ratioTrue), dict(typeRandomFlip), dict(typeNormalize, **img_norm_cfg), dict(typePad, size_divisor32), dict(typeImageToTensor, keys[img]), dict(typeCollect, keys[img]), ]) ]3.x 的 Mask R-CNN test_pipelinetest_pipeline [ dict(typeLoadImageFromFile), dict(typeResize, scale(1333, 800), keep_ratioTrue), dict( typePackDetInputs, meta_keys(img_id, img_path, ori_shape, img_shape, scale_factor)) ]注意测试流水线中PackDetInputs显式声明了meta_keys这些元信息图像 ID、路径、原始尺寸、网络输入尺寸、缩放因子会被写入DetDataSample的元数据中供后处理与评测使用。从源码看PackDetInputs在 mmdet/datasets/transforms/formatting.py 中实现默认meta_keys还包括flip与flip_directionL50-L52其mapping_tableL44-L48会把gt_bboxes → bboxes、gt_bboxes_labels → labels、gt_masks → masks最终封装进DetDataSample.gt_instances并处理gt_ignore_flags区分正常与忽略的实例L88-L117。2.3 数据增强变换的 2.x → 3.x 映射表官方文档还给出了一批重构后数据增强变换的对应关系迁移时按表替换即可名称2.x 配置3.x 配置Resizedict(typeResize, img_scale(1333, 800), keep_ratioTrue)dict(typeResize, scale(1333, 800), keep_ratioTrue)RandomResizedict(typeResize, img_scale[(1333, 640), (1333, 800)], multiscale_moderange, keep_ratioTrue)dict(typeRandomResize, scale[(1333, 640), (1333, 800)], keep_ratioTrue)RandomChoiceResizedict(typeResize, img_scale[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], multiscale_modevalue, keep_ratioTrue)dict(typeRandomChoiceResize, scales[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], keep_ratioTrue)RandomFlipdict(typeRandomFlip, flip_ratio0.5)dict(typeRandomFlip, prob0.5)可以总结出三条规律img_scale统一改名为scale多尺度场景下对应参数名为scalesmultiscale_mode参数被废除取而代之的是语义更明确的独立变换类型multiscale_moderange→RandomResizemultiscale_modevalue→RandomChoiceResizeflip_ratio改名为prob。这些变换的实现集中在 mmdet/datasets/transforms/transforms.pyRandomResize、RandomChoiceResize、RandomFlip等类均注册于此验证/测试时同名的测试变换类则位于 mmdet/datasets/transforms/transforms.py 对应的 test time 变换注册项中如Resize、RandomFlip同时承担训练与测试角色。2.4 Evaluator评测从数据集中解耦独立成 val_evaluator / test_evaluator3.x 中精度评测不再与数据集绑定而是通过独立的 EvaluatorMetric完成。配置拆为两部分val_evaluator验证集评测与test_evaluator测试集评测对应 2.x 的evaluation字段。官方给出的主要评测器对照如下评测指标2.x 配置3.x 配置COCOdata dict(valdict(typeCocoDataset, ann_file...)); evaluation dict(metric[bbox, segm])val_evaluator dict(typeCocoMetric, ann_file..., metric[bbox, segm], format_onlyFalse)Pascal VOCdata dict(valdict(typedataset_type, ann_file...VOC2007/ImageSets/Main/test.txt)); evaluation dict(metricmAP)val_evaluator dict(typeVOCMetric, metricmAP, eval_mode11points)OpenImagesdata dict(valdict(typeOpenImagesDataset, ann_file..., img_prefix..., label_file..., hierarchy_file..., meta_file..., image_level_ann_file...)); evaluation dict(interval1, metricmAP)val_evaluator dict(typeOpenImagesMetric, iou_thrs0.5, ioa_thrs0.5, use_group_ofTrue, get_supercategoryTrue)CityScapesdata dict(valdict(typeCityScapesDataset, ann_file..., img_prefix...)); evaluation dict(metric[bbox, segm])val_evaluator [dict(typeCocoMetric, ann_file..., metric[bbox, segm]), dict(typeCityScapesMetric, ann_file..., seg_prefix..., outfile_prefix./work_dirs/cityscapes_metric/instance)]关键迁移点评测不再依赖数据集类型例如 CityScapes 场景可以同时挂CocoMetric输出 bbox/segm AP与CityScapesMetric输出 CityScapes 官方格式的 instance 指标两者都只需要提供ann_file。val_evaluator本身可以是一个 dict 或 dict 列表。OpenImages 的元数据配置大幅简化2.x 需要手写label_file、hierarchy_file、meta_file、image_level_ann_file等一长串文件路径3.x 的OpenImagesMetric将这些文件作为数据集内置元数据管理配置面收敛为iou_thrs、ioa_thrs、use_group_of、get_supercategory等评测行为参数。这些评测器类分别实现在 mmdet/evaluation/metrics/coco_metric.py、voc_metric.py、openimages_metric.py、cityscapes_metric.py。format_onlyTrue的用途见《配置教程》当测试集没有标注文件时可用它只格式化并保存预测结果为 COCO json 提交文件同时指定outfile_prefix输出路径test_evaluator val_evaluator是绝大多数配置的默认写法仓库的 configs/base/datasets/coco_instance.pyL67-L73即为此模式并在注释中给出了测试集提交场景的完整示例。三、训练与测试配置迁移runner evaluation → train_cfg / val_cfg / test_cfg2.x 用runner指定训练循环EpochBasedRunner / IterBasedRunner用evaluation.interval指定验证间隔3.x 改为 MMEngine 的 Loop 体系拆分为三个字段2.x 配置runner dict( typeEpochBasedRunner, # Type of training loop max_epochs12) # Maximum number of training epochs evaluation dict(interval2) # Interval for evaluation, check the performance every 2 epochs3.x 配置train_cfg dict( typeEpochBasedTrainLoop, # Type of training loop max_epochs12, # Maximum number of training epochs val_interval2) # Interval for validation, check the performance every 2 epochs val_cfg dict(typeValLoop) # Type of validation loop test_cfg dict(typeTestLoop) # Type of testing loop迁移要点runner.typemax_epochs→train_cfg.typeEpochBasedTrainLoopmax_epochsevaluation.interval→train_cfg.val_interval语义完全对应每 N 个 epoch 验证一次验证与测试循环分别由val_cfg、test_cfg显式声明类型固定为ValLoop/TestLoop若采用基于迭代的训练则将train_cfg换成typeIterBasedTrainLoopmax_iters同时param_scheduler全部改为by_epochFalse、sampler 换成InfiniteSampler、checkpoint 钩子与log_processor均改为迭代制完整示例见《配置教程》Iter-based config一节仓库中对应 configs/retinanet/retinanet_r50_fpn_90k_coco.py。四、优化配置迁移optim_wrapper 与 param_scheduler4.1 优化器与梯度裁剪optimizer optimizer_config → optim_wrapper2.x 中优化器配置在optimizer字段梯度裁剪在optimizer_config字段3.x 将两者统一收进optim_wrapper并支持通过切换 wrapper 类型启用混合精度训练2.x 配置optimizer dict( typeSGD, # Optimizer: Stochastic Gradient Descent lr0.02, # Base learning rate momentum0.9, # SGD with momentum weight_decay0.0001) # Weight decay optimizer_config dict(grad_clipNone) # Configuration for gradient clipping, set to None to disable3.x 配置optim_wrapper dict( # Configuration for the optimizer wrapper typeOptimWrapper, # Type of optimizer wrapper, you can switch to AmpOptimWrapper to enable mixed precision training optimizerdict( # Optimizer configuration, supports various PyTorch optimizers typeSGD, # SGD lr0.02, # Base learning rate momentum0.9, # SGD with momentum weight_decay0.0001), # Weight decay clip_gradNone, # Configuration for gradient clipping, set to None to disable )迁移要点optimizer整体嵌套进optim_wrapper.optimizer参数type/lr/momentum/weight_decay原样保留支持 PyTorch 全部优化器optimizer_config.grad_clip→optim_wrapper.clip_gradNone表示关闭梯度裁剪需要裁剪时写法为clip_graddict(max_norm35, norm_type2)开启混合精度只需把type从OptimWrapper换成AmpOptimWrapper仓库中大量 AMP 配置如 configs/mask_rcnn/mask-rcnn_r50_fpn_amp-1x_coco.py即通过_base_覆盖optim_wrapper.type实现。4.2 学习率策略lr_config → param_scheduler2.x 用lr_config描述学习率策略policy、warmup、step、gamma 等3.x 的param_scheduler更贴近 PyTorch 的torch.optim.lr_scheduler且以列表形式支持多个调度器叠加。官方以 step 策略 线性 warmup 为例2.x 配置lr_config dict( policystep, # Use multi-step learning rate strategy during training warmuplinear, # Use linear learning rate warmup warmup_iters500, # End warmup at iteration 500 warmup_ratio0.001, # Coefficient for learning rate warmup step[8, 11], # Learning rate decay at which epochs gamma0.1) # Learning rate decay coefficient3.x 配置param_scheduler [ dict( typeLinearLR, # Use linear learning rate warmup start_factor0.001, # Coefficient for learning rate warmup by_epochFalse, # Update the learning rate during warmup at each iteration begin0, # Starting from the first iteration end500), # End at the 500th iteration dict( typeMultiStepLR, # Use multi-step learning rate strategy during training by_epochTrue, # Update the learning rate at each epoch begin0, # Starting from the first epoch end12, # Ending at the 12th epoch milestones[8, 11], # Learning rate decay at which epochs gamma0.1) # Learning rate decay coefficient ]映射关系一览policystep→ 列表中的MultiStepLRstep[8, 11]→milestones[8, 11]gamma原样保留warmuplinear→ 列表首位的LinearLRwarmup_iters500→end500warmup_ratio0.001→start_factor0.001每个调度器都通过by_epoch声明更新粒度warmup 按迭代False主体策略按 epochTrue通过begin/end声明作用区间因此 warmup 与主策略可以无缝拼接在同一时间轴上2.x 的policycosine对应 3.x 的CosineAnnealingLRpolicypoly对应PolyLR其余策略的迁移对照可参考 MMEngine 的参数调度器迁移文档见官方文档末尾指引。五、其他配置迁移5.1 保存 Checkpointcheckpoint_config / evaluation.save_best → default_hooks.checkpoint3.x 把 checkpoint 保存逻辑统一收进default_hooks.checkpointCheckpointHook并同时承载了 2.x 分散在checkpoint_config与evaluation中的职责功能2.x 配置3.x 配置设置保存间隔checkpoint_config dict(interval1)default_hooks dict(checkpointdict(typeCheckpointHook, interval1))保存最优模型evaluation dict(save_bestauto)default_hooks dict(checkpointdict(typeCheckpointHook, save_bestauto))保留最近 N 个模型checkpoint_config dict(max_keep_ckpts3)default_hooks dict(checkpointdict(typeCheckpointHook, max_keep_ckpts3))迁移要点interval、save_best、max_keep_ckpts三个参数语义在 2.x 与 3.x 间完全不变save_bestauto表示自动根据验证指标如coco/bbox_mAP挑选最优 checkpoint也可以写成save_bestcoco/bbox_mAP显式指定监控的指标名需要同时配置多个功能时只需在同一个CheckpointHook内合并字段default_hooks是字典custom_hooks是列表两者分工见《配置教程》default_hooks内是运行时必需的钩子timer、logger、param_scheduler、checkpoint、sampler_seed、visualization完整默认值见 configs/base/default_runtime.pycustom_hooks用于挂载用户自定义钩子。5.2 日志与可视化log_config / vis_backends → LoggerHook Visualizer3.x 中日志打印与可视化分别由 MMEngine 的 logger 与 visualizer 承担迁移对照如下功能2.x 配置3.x 配置设置日志打印间隔log_config dict(interval50)default_hooks dict(loggerdict(typeLoggerHook, interval50))可选log_processor dict(typeLogProcessor, window_size50)使用 TensorBoard 或 WandB 可视化log_config dict(interval50, hooks[dict(typeTextLoggerHook), dict(typeTensorboardLoggerHook), dict(typeMMDetWandbHook, init_kwargs{project: mmdetection, group: maskrcnn-r50-fpn-1x-coco}, interval50, log_checkpointTrue, log_checkpoint_metadataTrue, num_eval_images100)])vis_backends [dict(typeLocalVisBackend), dict(typeTensorboardVisBackend), dict(typeWandbVisBackend, init_kwargs{project: mmdetection, group: maskrcnn-r50-fpn-1x-coco})]visualizer dict(typeDetLocalVisualizer, vis_backendsvis_backends, namevisualizer)迁移要点日志打印log_config.interval→default_hooks.loggerLoggerHook的intervallog_processor.window_size用于对日志数值做滑动平均平滑默认 50by_epoch需与训练循环类型保持一致可视化后端2.x 的TensorboardLoggerHook、MMDetWandbHook等日志钩子 → 3.x 的TensorboardVisBackend、WandbVisBackend等可视化后端统一挂在visualizer.vis_backends列表下LocalVisBackend负责本地保存可视化结果init_kwargsproject、group 等 WandB 初始化参数写法基本保留可视化相关的完整使用教程见 可视化教程。5.3 运行时配置cudnn_benchmark / dist_params 等 → env_cfg resume2.x 散落的运行时字段在 3.x 被整理进env_cfg同时resume_from简化为布尔型resume2.x 配置cudnn_benchmark False opencv_num_threads 0 mp_start_method fork dist_params dict(backendnccl) log_level INFO load_from None resume_from None3.x 配置env_cfg dict( cudnn_benchmarkFalse, mp_cfgdict(mp_start_methodfork, opencv_num_threads0), dist_cfgdict(backendnccl)) log_level INFO load_from None resume False映射关系cudnn_benchmark、mp_start_method、opencv_num_threads、dist_params.backend全部并入env_cfgmp_cfg/dist_cfg子字段log_level、load_from保持不变load_from仅用于加载预训练权重不会恢复训练状态resume_from→resume3.x 中resumeTrue时若load_from指定了 checkpoint 则从该文件恢复否则自动恢复work_dir下最新的 checkpoint。env_cfg、default_hooks、vis_backends、visualizer、log_processor的默认值均在 configs/base/default_runtime.py 中维护多数迁移后的配置只需继承该文件即可无需逐项手写。六、迁移实战用一条命令验证配置合法性完成迁移后推荐用仓库自带的配置打印工具验证配置能否被正确解析与继承python tools/misc/print_config.py /PATH/TO/CONFIG该命令会输出继承展开后的完整配置详见《配置教程》Config file inheritance一节。迁移过程中还需注意三个常见的配置系统细节_delete_True继承_base_时若要整体替换某个字典字段例如把 Mask R-CNN 的 ResNet backbone 换成 HRNet必须在该字段前加_delete_True否则新旧键会做递归合并而非替换中间变量train_pipeline/test_pipeline等中间变量在子配置中修改后必须显式传回对应字段例如train_dataloader dict(datasetdict(pipelinetrain_pipeline))否则子配置的修改不会生效{{_base_.xxx}}可通过a {{_base_.model}}在子配置中复用基类变量。结语MMDetection 2.x → 3.x 的配置迁移表面上是一张字段对照表本质上是一次职责重构数据处理收归data_preprocessor运行阶段拆分为独立的 dataloader / loop / evaluator优化与调度对齐 PyTorch 原生 API日志与可视化交由 MMEngine 的 Hook 与 Visualizer 体系。掌握本文的映射关系与仓库源码依据后无论是手工改写 2.x 配置还是阅读并定制仓库中 configs 下 3.x 的数百个现有配置都将更加得心应手。对于更深入的数据流细节可继续阅读 数据流文档 与 TTA 文档。【免费下载链接】mmdetectionOpenMMLab Detection Toolbox and Benchmark项目地址: https://gitcode.com/gh_mirrors/mm/mmdetection创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
上一篇/下一篇内容由系统自动关联 返回资讯列表 →