0
$\begingroup$
optimizer=torch.optim.AdamW(list(model3.parameters())+list(model1.parameters())+list(model2.parameters())) 

optimizer.zero_grad()

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

loss=nn.BCELoss(prediction,labels)

loss.backward()

optimizer.step()

enter image description here

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

$\endgroup$
1
$\begingroup$

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)

$\endgroup$
2
  • $\begingroup$ How parameters of the models are updated. in what sequence parameters of the models are updated $\endgroup$ Jun 10 at 8:54
  • $\begingroup$ 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. $\endgroup$
    – noe
    Jun 10 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.