Can't use DistributedDataParallel for training the EncoderDecoderModel
Hey ,I want to fine-tune the EncoderDecoderModel with 4 GPUs . And I use DistributedDataParallel for parallel training.My code just like this:from transformers import EncoderDecoderModel, BertTokenizer
import torch
import argparse
import argparse
import torch.multiprocessing as mp
import torch.nn as nn
import torch.distributed as dist

def main():

     parser = argparse.ArgumentParser()

     args = parser.parse_args()

     args.max_src_len = 512

     args.max_dst_len = 128

     args.gpus = 4

     args.world_size = args.gpus

     args.epoches = 30

     mp.spawn(train, nprocs=args.gpus, args=(args,))

def train(gpu, args):

     rank = gpu

     dist.init_process_group(                                   

     backend='nccl',                                         

          init_method='tcp://127.0.0.1:23456',                                   

     world_size=args.world_size,                              

     rank=rank                                               

    )    

     torch.manual_seed(0)

     model = EncoderDecoderModel.from_pretrained("bert2bert")

     torch.cuda.set_device(gpu)

     model = model.to(gpu)

     optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

     model = nn.parallel.DistributedDataParallel(model,

                                                device_ids=[gpu])

     dataset_path = 'dataset/example.json'

     vocab_path = 'dataset/vocab.txt'

     dataset = CNNDataset(dataset_path, vocab_path, args)

     train_sampler = torch.utils.data.distributed.DistributedSampler(

     dataset,

     num_replicas=args.world_size,

     rank=rank

    )

     dataloader = DataLoader(dataset, batch_size=32, shuffle=False, 

     num_workers=0,

       pin_memory=True,

      sampler=train_sampler, collate_fn=collate_fn)

     for epoch in range(args.epoches):

          for src, dst in dataloader:

               src = torch.stack(src).to(gpu)

               dst = torch.stack(dst).to(gpu)

               mask = (src!=0)

               mask = mask.long()

               outputs = model(input_ids=src, attention_mask=mask, decoder_input_ids=dst, labels=dst, return_dict=True)

               loss, logits = outputs.loss, outputs.logits

               optimizer.zero_grad()

               loss.backward()

               optimizer.step()


if __name__ == '__main__':

     main()I got the following errors.– Process 0 terminated with the following error:Traceback (most recent call last):File “/home/LAB/maoqr/miniconda3/envs/py36/lib/python3.6/site-packages/torch/multiprocessing/spawn.py”, line 20, in _wrapfn(i, *args)File “/home/LAB/maoqr/yanghongzheng/demo_multi.py”, line 66, in trainoutputs = model(input_ids=src, attention_mask=mask, decoder_input_ids=dst, labels=dst, return_dict=True)File “/home/LAB/maoqr/miniconda3/envs/py36/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 722, in _call_implresult = self.forward(*input, **kwargs)File “/home/LAB/maoqr/miniconda3/envs/py36/lib/python3.6/site-packages/torch/nn/parallel/distributed.py”, line 528, in forwardself.reducer.prepare_for_backward([])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 argumentfind_unused_parameters=Truetotorch.nn.parallel.DistributedDataParallel; (2) making sure allforwardfunction 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’sforwardfunction. Please include the loss function and the structure of the return value offorwardof your module when reporting this issue (e.g. list, dict, iterable).How can I fix this issue ?It seems like the outputs of the EncoderDeocderModel can’t  be located.Thank you very much.
2020-10-26T09:28:03Z
As the error tells you, try addingfind_unused_parameters=TruetoDistributedDataParallel(). That should help. Read morehere.
2020-10-27T08:27:19Z
Thank you very much !