# How to train 3 models with single loss function in pytorch

optimizer=torch.optim.AdamW(list(model3.parameters())+list(model1.parameters())+list(model2.parameters()))

prediction=model3(model1(x)+model2(x))

loss=nn.BCELoss(prediction,labels)

loss.backward()

optimizer.step()


How can I update parameters of all three models with single loss

Yes, there is no problem with the code you showed. The gradients are propagated all the way up, unless you do something to prevent it (e.g. .detach(), param.requires_grad = False, etc)
• When you compute the forward pass, the information about which operations have been performed is stored. When you invoke loss.backward(), the gradients are computed (back-propagation) using the stored operations information; these gradients are then saved in each parameter's .grad attribute. When you invoke optimizer.step(), the parameters registered in the optimizer are updated; the order in which they are updated is irrelevant, because the gradients have already been computed, from the loss node up to the beginning of the operations chain.