mmdetection学习记录之报错解决汇总

报错1:

RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by (1) passing the keyword argument find_unused_parameters=True to torch.nn.parallel.DistributedDataParallel; (2) making sure all forward function outputs participate in calculating loss. If you already have done the above two steps, then the distributed data parallel module wasn’t able to locate the output tensors in the return value of your module’s forward function. Please include the loss function and the structure of the return value of forward of your module when reporting this issue (e.g. list, dict, iterable).

这个是我在进行多GPU训练时报错的,上网查了一些情况 以及 上述报错提醒后 得知可能是如下的错误:

  • 并行运算产生的问题
  • 代码问题,比如通道数不对、forward中的所有通道是否都使用了、更新损失时产生的问题

为了排除,我先单GPU训练了一下,发现报错没有了,因此肯定不是代码问题了。
随后在Github上看到有人提出的方法:use the find_unused_parameters=True option when wrapping the model in torch.nn.parallel.DistributedDataParallel.
即修改 mmdet/apis/train.py 下的114行代码

# put model on gpus
    # 基于是否使用分布式训练,初始化对应的DataParallel
    if distributed:
        # find_unused_parameters = cfg.get('find_unused_parameters', False)  # 原代码
        find_unused_parameters = True  # 修改后代码
        # Sets the `find_unused_parameters` parameter in
        # torch.nn.parallel.DistributedDataParallel
        model = MMDistributedDataParallel(
            model.cuda(),
            device_ids=[torch.cuda.current_device()],
            broadcast_buffers=False,
            find_unused_parameters=find_unused_parameters)
    else:
        model = MMDataParallel(
            model.cuda(cfg.gpu_ids[0]), device_ids=cfg.gpu_ids)

成功解决!

报错2

one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.HalfTensor [2, 256, 12, 12]], which is output 0 of AddBackward0, is at version 3; expected version 2 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

在修改了代码后报错,那么一想肯定是刚才改的代码有问题。

            laterals[i - 1] += F.interpolate(
                laterals[i], size=prev_shape, mode='nearest') 
            add_atten = self.up2bottom_cbams[i-1](laterals[i-1]) 
            laterals[i-1] += add_atten

个人认为是因为在Python中对象的赋值是默认浅拷贝

#也就是 self.up2bottom_cbams[i-1](laterals[i-1]) 修改了 laterals[i-1],造成了在进行梯度计算时出错
#因此需要对其进行深拷贝,复制一份新的对象出来进行操作
            laterals[i - 1] += F.interpolate(
                laterals[i], size=prev_shape, mode='nearest')  
            add_atten = self.up2bottom_cbams[i-1](laterals[i-1].clone())
            laterals[i-1] += add_atten

最后也如愿解决了

你可能感兴趣的:(mmdetection,学习,pytorch,python,mmdetection)