Multiple forward before backward, where backward depends on all forward calls

bananacode: <p>I’d like to implement something similar to <a href="https://arxiv.org/pdf/1807.03146.pdf" rel="nofollow noopener">KeypointNets</a> multi-view consistency and rotation loss. The gist of it is as follows:</p>
<p>Let M be our model, I an image and T a transformation matrix. For the multi-view consistency loss, one has a affine transformation matrix T and you’d like to impose equivariance upon the model wrt to T: M(T<em>I) == T</em>M(I)</p>
<p>Similarly for the rotation loss, given M(T*I) and M(I), one would like to estimate T with T_ and enforce T == T_.</p>
<p>The pseudo code I’ve implemented looks as follows:</p>
<pre><code class="lang-auto">y_1 = M(I)
y_2 = M(T*I)
mvc_loss = ||T*y_1 - y_2||^2
T_ = estimate_transformation(y_1, y_2)
rot_loss = ||T - T_||^2
loss = mvc_loss + rot_loss
loss.backward()
optim.step()
</code></pre>
<p>I’ve seen the threads <a href="https://discuss.pytorch.org/t/multiple-forward-before-backward-call/20893">Multiple forward before backward call</a>, <a href="https://discuss.pytorch.org/t/how-to-implement-accumulated-gradient-in-pytorch-i-e-iter-size-in-caffe-prototxt/2522">How to implement accumulated gradient in pytorch (i.e. iter_size in caffe prototxt)</a> and <a href="https://discuss.pytorch.org/t/how-to-implement-accumulated-gradient/3822">How to implement accumulated gradient？</a>, regarding calling multiple forwards before backpropagating. However, they all call backward() directly after each forward call. I need to call forward twice before being able to call backward, as the loss depends on both forward calls. I’ve been getting NaNs, and am wondering if I’m handling this correctly.</p>
<p>Can anybody confirm that what I’m doing is correct? If it isn’t could someone indicate what the correct way would be?</p>
<p>Thanks!</p>

bananacode: <p>Anyone have an answer?</p>

JuanFMontesinos: <p>But what u wanna do is not difficult.<br>
You have just to create an additional nn.Module class like:</p>
<pre><code class="lang-auto"> model = ur_model #nn.Module
class double_forward(nn.Module):


     init
        self.single=model
     forward(I,T):
        y_1 = M(I)
        y_2 = M(T*I)
       and so on
</code></pre>
<p>In the end u can have as many outputs as u want with ur custom loss. You can run the module as many times as u want (but define it only once) paying attention to the order not to create a wrong graph</p>

bananacode: <p>Thank you for your response. So the code snippet which I posted is correct?</p>

JuanFMontesinos: <aside class="quote no-group quote-modified" data-username="bananacode" data-post="1" data-topic="24272">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/b/b487fb/48.png" class="avatar"> bananacode:</div>
<blockquote>
<p>y_1 = M(I) y_2 = M(T<em>I) mvc_loss = ||T</em>y_1 - y_2||^2 T_ = estimate_transformation(y_1, y_2) rot_loss = ||T - T_||^2 loss = mvc_loss + rot_loss loss.backward() optim.step()</p>
</blockquote>
</aside>
<p>Well I’m not a super expert in PyTorch but I would recommend you to warp both forward passes in a nn.Module like this:</p>
<pre><code class="lang-auto">=================defining model=================
class My_model(nn.Module):
    def __init__(self):
        super(Audio_Synthesizer, self).__init__()
        self.model = your_original_model
   def forward(self, I, T):
        y_1 = self.model(I)
       y_2 = self.model(T*I)
       T_ = estimate_transformation(y_1, y_2)
mvc_loss = ||T*y_1 - y_2||^2  #Use torch loss/functions to do this
rot_loss = ||T - T_||^2   #Use torch loss/ functions to do this
loss =torch.add(mvc_loss , rot_loss)
       return T_,y_1,y_2
===========training stage========================



loss = my_custom_loss(T,T_,y_1,y_2)
optimizer.zero_grad()
loss.backward()
optim.step()
</code></pre>
<p>About the loss I would recommend you to read<br>
<a href="https://discuss.pytorch.org/t/solved-what-is-the-correct-way-to-implement-custom-loss-function/3568/4" class="inline-onebox">[Solved] What is the correct way to implement custom loss function? - #4 by Hengck</a>?</p>
<p>You can either build a custom loss function (upper link link)<br>
or to include it inside the bigger nn</p>
<pre><code class="lang-auto">=================defining model=================
class My_model(nn.Module):
    def __init__(self):
        super(Audio_Synthesizer, self).__init__()
        self.model = your_original_model
   def forward(self, I, T):
        y_1 = self.model(I)
       y_2 = self.model(T*I)
       T_ = estimate_transformation(y_1, y_2)
       mvc_loss = ||T*y_1 - y_2||^2
       rot_loss = ||T - T_||^2
       loss =torch.add(mvc_loss , rot_loss)
       return loss, others
===========training stage========================
optimizer.zero_grad()
loss.sum() #if using dataparallel
loss.backward()
optim.step()
</code></pre>
<p>I don’t really know how it would affect to perform operations over the loss out of autograd class or nn.module class. Remember any operation you do must be done using autograd compatible functions (this is, native  differentiable torch functions )</p>

bananacode: <p>Why would you recommend to wrap it in a custom class? Just for readability? It shouldnt affect the behaviour otherwise as far as I can see</p>

sunny_wang: <p>I have the same question, have you managed to sort it out?</p>

bananacode: <p>No, unfortunately not. I’ve since abandoned the project. Let me know if you figure it out.</p>

mars747: <p>Wrapping in a custom class works for me I can confirm. However, it does not seem to behave well with batchnorm. Is one forced to use InstanceNorm in this case?</p>

hoangcuong2011: <p>I noticed something off today with similar <a href="https://discuss.pytorch.org/t/loss-does-not-decrease-when-the-model-is-called-twice/98493">problem</a>. Perhaps the root of the problem is the same to your case: Calling the forward function multiple times is not well-behaved.</p>