Executing two models in parallel while utilizing the torch.no_grad() function to disable gradient computation during inference

Hello everyone,

I’m trying to make a knowledge distillation between two losses but I encounter the following issue:

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_parameters=Truetotorch.nn.parallel.DistributedDataParallel; (2) making sure all forwardfunction 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 offorward of your module when reporting this issue (e.g. list, dict, iterable).

I am currently running two models simultaneously, with one of the models being solely for inference purposes. However, it appears that the parameters from this inference model are being combined with the parameters of the main model, which is not my intention.

I tried with:

        with torch.no_grad():
            self.net = FeatureExtractor(pipeline.extractor, device, {'resize': 1280})

tried to add “find_unused_parameters=True”, but without solving the problem.

I’m using pytorch lightning.

Do you have any idea what cloud be the problem?


You might want to wrap the inference model into torch.nn.parallel.DistributedDataParallel.no_sync which will disable the gradient synchronization.