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

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: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
 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

hello everyone, I have encountered a problem
When running code outputs=model (enc_inputs), the above error occurred. I am confused because there is no problem running the code directly in Python train/main.py without modification, but there is an error when running it in accelerate launch.I have checked the shape of the tensor and there is no problem

One interesting thing is that I used the encoder part of the transformer model. When I delete the encoder, the above error message will appear (at this time, only the embedded and linear models can run in a normal Python environment)

my code is
model


import torch.nn as nn

from train.datasets import *
d_model = 128
d_ff = 64
d_k = d_v = 64
n_layers = 6
n_heads = 8

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')


class Transformer(nn.Module):
    def __init__(self):
        super(Transformer, self).__init__()
        self.device = device
        self.src_emb = nn.Embedding(src_vocab_size, d_model)
        self.transformer_encoder = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(d_model=d_model, nhead=n_heads, dim_feedforward=d_ff, batch_first=True),
            num_layers=n_layers,
        )
        self.projection = nn.Linear(d_model, tgt_vocab_size, bias=True)

    def forward(self, src):
        src_padding_mask = (src == 0)
        src_mask = nn.Transformer.generate_square_subsequent_mask(src.size(1)).bool().to(self.device)
        memory = self.src_emb(src)
        # memory = self.transformer_encoder(memory, src_key_padding_mask=src_padding_mask, mask=src_mask)
        output = self.projection(memory)
        return output.view(-1, output.shape[-1])

memory = self.transformer_encoder(memory, src_key_padding_mask=src_padding_mask, mask=src_mask) this code delete will be error

my main code is

accelerator = Accelerator()
model = Transformer()
optimizer = optim.Adadelta(model.parameters(), lr=0.1, rho=0.9, eps=1e-6, weight_decay=0)
# optimizer = Lion(model.parameters(), lr=5e-6, weight_decay=1e-2)
criterion = nn.CrossEntropyLoss(ignore_index=0)
model, optimizer, train_loader, test_loader= accelerator.prepare(model, optimizer, train_loader, test_loader)

for epoch in range(0, 10000):
    for Step, (enc_inputs, dec_inputs) in enumerate(train_loader):
        enc_inputs, dec_inputs = enc_inputs.cuda(), dec_inputs.cuda()
        outputs = model(enc_inputs)
        loss = criterion(outputs, dec_inputs.view(-1))
        accelerator.backward(loss)
        optimizer.step()
        optimizer.zero_grad()

Can someone tell me why the error occurred? Thank you very much.

I fix this with getting error while training LayoutLMV2 model on multi gpu setup · Issue #648 · huggingface/accelerate (github.com)

by input this code

from accelerate import DistributedDataParallelKwargs
accelerator = Accelerator(kwargs_handlers=DistributedDataParallelKwargs(find_unused_parameters=True)

this code can be run.

but I still have some question, why my code without this still can run,and why i need this code. I will keep study.

You should follow this suggestion and check which parameter did not receive gradients.
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

With accelerate, it seems that you are using the multi gpu setup (DDP) whereas when you just run it with python {myscript.py}, it will use the single gpu setup. Hence, the issue.