Pytorch DistributedDataParallel 使用中的一些bug和解决参考
问题背景: 代码在单卡上跑的好好的,没啥问题。 在DataParallel 上跑的也好好的,也没啥问题。 一用 DDP 就各种问题:
-
问题1: DDP 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_para meters=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 va lue of your module’s forward function. Please include the loss function and the structure of the return value of forward of your module whe n reporting this issue (e.g. list, dict, iterable).
- 遇到这种问题,先放上建议链接:
- https://discuss.pytorch.org/t/process-got-stuck-when-set-find-unused-parameters-true-in-ddp/106078
- 就是说,你的模型里,可能有部分的参数是没有参与loss 计算的。这种情况很常见,比如可能一个模型结合了多个任务,在taskA的时候,某几层运算,并参与loss计算。在taskB的时候,可能另外几层是不参与计算的。在这种情况下,就会报这个错误。
- 解决方案a:首先,在上面说的情况下可以让所有参数都推理,然后把不想更新的模型的参数,乘上权重为0 的loss,这样就能运行,问题是会增加一些无关的开支和运算。(亲测可用)
-
问题1的进阶问题:对于问题1,还可能是因为输出了多个outputs,但是只有部分outputs参与了运算。也可能会出现这个问题。那么多个outputs是主要原因吗,或者说这个多个outputs能不能解决?本人发现某种方式的写法,可以避免这个问题:
-
if 条件A:
pred,_ = model(。。。)
loss = Loss(pred,gt)
loss+= Loss(pred,_)*0
else:
pred = model(。。。)
loss = Loss(pred,gt)
就是说在一个条件范围里面,这样写,就多个outputs也是能够计算的,而如果独立出来,就会报错。
-
问题2: #Some NCCL operations have failed or timed out. Due to the asynchronous nature of CUDA kernels, subsequent GPU operations might run on corrupted/incomplete data. 这个问题的原因可能是多个站点的交互出现了问题,在计算完loss 之后,需要对其进行reduce。可以参照:https://github.com/rosinality/stylegan2-pytorch
def reduce_loss_dict(loss_dict):
world_size = get_world_size()
if world_size < 2:
return loss_dict
with torch.no_grad():
keys = []
losses = []
for k in sorted(loss_dict.keys()):
keys.append(k)
losses.append(loss_dict[k])
losses = torch.stack(losses, 0)
dist.reduce(losses, dst=0)
if dist.get_rank() == 0:
losses /= world_size
reduced_losses = {k: v for k, v in zip(keys, losses)}
return reduced_losses
否则就会出现上面的问题2.
|