运行代码时出现了错误:
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
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”,然后就会出现哪里未更新:
然后在你的模型中仔细检查forward函数和init函数:
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参数含义 - 知乎