windows 配置Co-DETR踩坑笔记

本文讲述了在Windows系统上使用mmcv进行模型训练时遇到的各种问题,如Git访问错误、mmtracking安装、依赖库报错、CUDA内存不足等,并提供了相应的解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

         我用的是windows系统单卡训练,所以没有用官方的bash脚本,而是直接使用train.py进行训练。主要问题集中在mmcv的安装上。

1、报错:subprocess-exited-with-error

完整报错:fatal: unable to access 'https://github.com/open-mmlab/mmtracking/': GnuTLS recv error (-110): The TLS connection was non-properly terminated.
  error: subprocess-exited-with-error
  
  × git reset --hard -q e79491ec8f0b8c86fda947fbaaa did not run successfully.
  │ exit code: 128
  ╰─> See above for output.
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× git reset --hard -q e79491ec8f0b8c86fda947fbaaa did not run successfully.
│ exit code: 128
╰─> See above for output.

        使用pip install -r requirements.txt配置环境时,无法访问https://github.com/open-mmlab/mmtracking。

解决方法:去https://github.com/open-mmlab/mmtracking#egg=mmtrack下载源码,把下载源码解压到python安装包的目录或不会被删除的目录,进入到解压的目录,输入

pip install -e .

通过源码安装mmtracking。 

2、from mmcv.ops import RoIPool报错

        一般是直接pip install mmcv-full或者pip install mmcv时会出现这个错误。

解决方法:

pip install mmcv-full==1.5.0 -f https://download.openmmlab.com/mmcv/dist/cu115/torch1.11.0/index.html

(上面的cu115/torch1.11.0改成你自己的版本)

3、报错:from typing import Literal, ImportError: cannot import name ‘Literal’

        主要是因为只有Python 3.8 及更高版本才支持typing.Literal我按照官方推荐的环境,用的是python 3.7,所以不支持typing.Literal。

解决办法:

在最后一行报错的vison_transformer.py中,去除from typing import 中的Literal并加入如下代码:
try:
    from typing import Literal
except ImportError:
    try:
        from typing_extensions import Literal
    except ImportError:
        raise ImportError("Cannot import 'Literal' from 'typing'")

4、报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd3 in position 0: invalid continuation byte

解决方法:

尝试不同的编码方式,或者在最后一行报错的env.py中,

env_info['MSVC'] = cc.decode(encoding).partition('\n')[0].strip()改为

env_info['MSVC'] = cc.decode(encoding,'ignore').partition('\n')[0].strip()

5、报错:RuntimeError: CUDA error: no kernel image is available for execution on the device

完整报错:RuntimeError: CUDA error: no kernel image is available for execution on the device
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.

        这个问题卡了我最久,先是重装了pytorch、torchvision和cuda,没有用。后面又卸载并改装不同cuda版本的pytorch也没用,最后卸载了mmcv,装了更高版本的mmcv,成功解决了问题。(之前报错用的是官方的mmcv==1.5.0,换成了1.6.0版本解决问题)

6、训练自己的数据集

        先将自己的数据集转换成coco数据集,再去对应的_base_配置中修改data_root变量为自己的coco数据集路径。(我这里是coco_detection.py)

        然后在该文件下分别修改train,test,val下ann_file和img_prefix的值(训练的batch_size在这里设置会被后面继承的config文件覆盖掉)。

        在配置文件中将所有的num_classes修改为自己的类别数。

        在mmdet/core/evaluation/class_names.py修改coco_classes函数:return['自己数据集的类']:

在mmdet\datasets\coco.py修改CocoDataset类中的CLASSES=('自己数据集的类')。

7、报错:RuntimeError: CUDA out of memory.

完整报错:RuntimeError: CUDA out of memory.Tried to allocate 490.00 MiB (GPU 0; 6.00 GiB total capacity; 5.82 GiB already allocated; 0 bytes free; 5.86 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

         batchsize过大,显卡显存不足。

解决方法:

需要在配置文件中将samples_per_gpu调小。(不知道为什么,我6g的显存,batchsize最大只能设为1,有知道的可以在评论区说一下)

data = dict(  ##这里samples_per_gpu/workers_per_gpu是batch_num
    samples_per_gpu=2,
    workers_per_gpu=1,
    train=dict(filter_empty_gt=False, pipeline=train_pipeline),
    val=dict(pipeline=test_pipeline),
    test=dict(pipeline=test_pipeline))

成功训练

### 如何在自定义数据集上训练Co-DETR模型 为了在自定义数据集上训练Co-DETR模型,需遵循一系列特定的操作流程来准备环境、处理数据以及调整配置文件。以下是详细的指南: #### 准备工作 确保安装必要的依赖库并设置好开发环境。通常情况下,这涉及到创建虚拟环境和安装PyTorch及相关工具包。 ```bash conda create -n detr_env python=3.8 conda activate detr_env pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113 ``` #### 构建数据集 针对自定义的数据集,首先需要将其转换成适合Co-DETR使用的格式。一般而言,这意味着要按照COCO风格标注图像,并准备好相应的JSON文件描述这些标签信息[^2]。 假设已经有一个名为`custom_dataset.json`的文件位于项目目录下的`datasets/custom/annotations/`位置,则可以继续下一步操作。 #### 修改配置文件 找到源码中的默认参数设定部分(通常是`.yaml`或类似的配置文件),根据实际情况修改其中关于输入尺寸、批量大小等超参的内容。特别注意的是类别的数量应当反映出自定义数据集中存在的不同种类物体数目加上一个额外表示背景或其他未分类项的选择[^1]。 例如,在`configs/detr.yaml`中有如下字段可能需要更改: ```yaml num_classes: 91 # 对于COCO来说是这样;对于新的数据集应改为实际类别数加一 batch_size_per_gpu: 2 lr_backbone_names: ["backbone"] ... ``` #### 编写数据加载器 编写Python脚本来读取上述提到过的JSON文件作为输入,并实现Dataset子类用于迭代访问每一张图片及其对应的边界框坐标与类别ID。这部分逻辑可以直接借鉴官方提供的例子来做适当改动即可满足需求。 #### 开始训练过程 最后一步就是调用train函数启动整个学习周期了。在此之前记得确认所有路径都指向正确的地方并且GPU资源可用。如果一切顺利的话,应该能看到损失逐渐下降的趋势图以及其他监控指标的变化情况。 ```python from models.detection import build_model_main as build_detr import util.misc as utils import datasets import argparse import datetime import json import random import time from pathlib import Path import numpy as np import torch from torch.utils.data import DataLoader, DistributedSampler def main(args): ... model = build_detr.build(args) device = torch.device(args.device) dataset_train = build_dataset(image_set='train', args=args) sampler_train = DistributedSampler(dataset_train) if args.distributed else None data_loader_train = DataLoader( dataset_train, batch_size=args.batch_size, shuffle=(sampler_train is None), num_workers=args.num_workers, collate_fn=utils.collate_fn, drop_last=True, sampler=sampler_train ) output_dir = Path(args.output_dir) checkpoint = torch.load(args.resume, map_location='cpu') model_without_ddp.load_state_dict(checkpoint['model']) print("Start training") start_time = time.time() for epoch in range(args.start_epoch, args.epochs): train_stats = train_one_epoch(model, criterion, data_loader_train, optimizer, device, epoch, args.clip_max_norm) lr_scheduler.step() if args.output_dir: checkpoint_paths = [output_dir / 'checkpoint.pth'] if (epoch + 1) % args.lr_drop == 0 or (epoch + 1) % 5 == 0: checkpoint_paths.append(output_dir / f'checkpoint{epoch:04}.pth') for checkpoint_path in checkpoint_paths: utils.save_on_master({ 'model': model_without_ddp.state_dict(), 'optimizer': optimizer.state_dict(), 'lr_scheduler': lr_scheduler.state_dict(), 'epoch': epoch, 'args': args, }, checkpoint_path) total_time = time.time() - start_time ... if __name__ == '__main__': parser = argparse.ArgumentParser('DETR training and evaluation script', parents=[get_args_parser()]) args = parser.parse_args() if args.output_dir: Path(args.output_dir).mkdir(parents=True, exist_ok=True) main(args) ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值