运行代码时出现了错误:
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 passing the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`, and by
making sure all `forward` function outputs participate in calculating loss.
If you already have done the above, 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).
Parameter indices which did not receive grad for rank 0: 10
In addition, you can set the environment variable TORCH_DISTRIBUTED_DEBUG to either INFO or DETAIL to print out information about which particular parameters did not receive gradient on this rank as part of this error
[2024-04-04 11:17:04,182] torch.distributed.elastic.multiprocessing.api: [ERROR] failed (exitcode: 1) local_rank: 0 (pid: 4650) of binary: /home/mapengsen/anaconda3/envs/mocov3/bin/python
意思是你的模型有的参数并没有参与更新。
解决办法一:【但是会导致额外的开销】
其中在DDP中的一个解决办法是:
find_unused_parameters=True
DDP会自动检测并处理未参与前向传播的参数
find_unused_parameters 介绍:
如果模型的输出有不需要进行反传的(比如部分参数被冻结/或者网络前传是动态的)【如果有forward的返回值如果不在计算loss的计算图里】,设置此参数为True。如果你的代码运行后卡住某个地方不动,基本上就是该参数的问题,设置为find_unused_parameters=True 就可以了
缺陷:
find_unused_parameters=True 的设置会带来额外的运行时开销(而且还不小)。
解决办法二:【深度解决】
第一步:
这个原因其实是你的模型有些参数没有参与计算,所以你应该先找到哪些参数没有被更新:
具体参考:查看模型的哪些梯度/参数被更新了_torch.optim怎么查看网络参数是否加入梯度更新-CSDN博客
1)方法一:
for name, param in self.model.named_parameters():
if param.grad is None:
print("The None grad model is:")
print(name)
2)方法二:
在你的运行命令之前加上“TORCH_DISTRIBUTED_DEBUG=DETAIL”,然后就会出现哪里未更新:
第二步:
错误原因:
在使用nn.Module的__init__方法时,如果使用self.xx这样的语句定义了层,但是这个层的计算结果后续没有用来计算loss,或者这个self层没有使用,都会导致标题所述的报错
只需要在你的模型中仔细检查forward函数和init函数,check 你的 __init__() 方法中是否存在self参数,在 forward 中没有使用的,注释掉即可。
总结来看:
其实直接设置find_unused_parameters=True 会更好一些,也更符合逻辑一些,这样你也不用修改很多的代码,同时这种方式会让forward中的if -else书写更轻松
RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one._多gpu并行报错 expected to have finished reduction in th-CSDN博客
Pytorch分布式训练错误_runtimeerror: expected to have finished reduction -CSDN博客
解决pytorch报错——RuntimeError: Expected to have finished reduction in the prior iteration...-CSDN博客
PyTorch分布式训练DDP中的find_unused_parameters参数含义 - 知乎