问题背景:
代码在单卡上跑的好好的,没啥问题。
在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).
问题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.