Jacobian functional API batch-respecting Jacobian

murph213: <p>I am hoping to get Jacobians in a way that respects the batch, efficiently</p>
<p>Given a batch of b (vector) predictions <strong>y</strong>_1,…,<strong>y</strong>_b, and inputs <strong>x</strong>_1 … <strong>x</strong>_b, I want to compute the Jacobians of <strong>y</strong>_i wrt <strong>x</strong>_i.  In other words, I want a Jacobian of the output wrt input for each pair in the batch.</p>
<p>One might try the following:</p>
<pre><code class="lang-auto">import torch
import torch.nn as nn
# Load the experimental api 
# https://github.com/pytorch/pytorch/blob/master/torch/autograd/functional.py
from experimental_api import jacobian

in_dim = 5
batch_size = 3
hidden_dim = 2
out_dim = 10

f = nn.Sequential(nn.Linear(in_dim, hidden_dim), nn.Sigmoid(), nn.Linear(hidden_dim, out_dim))
x = torch.randn(batch_size, in_dim)

result = jacobian(f, x)
result.shape
</code></pre>
<blockquote>
<p>torch.Size([3, 10, 3, 5])</p>
</blockquote>
<p>In this case, I wanted a <code>result</code> with shape <code>(batch_size, out_dim, in_dim) = (3, 10, 5)</code> but instead got extra dimensions.  In fact, PyTorch is considering <code>x</code> as just one input matrix rather than a batch of several vectors.  This leads to redundant calculation such as the derivatives of target 2 wrt input 1.</p>
<p>Clearly, I could do a loop like <code>jacobian(f, x_row) for x_row in x</code> but that would no longer use the GPU effectively.  Can anyone propose an efficient solution?</p>

albanD: <p>Hi,</p>
<p>the functional API works at the autograd level and so is not aware of things like batch size.<br>
Supporting this kind of use case is planned to be supported efficiently by using vmap with the functional API.</p>
<p>If you’re using a regular neural net, the simplest thing to do here is just to take the diagonal of the full jacobian you get (using dim1=0 and dim2=2). It does lead to useless computations but not that much.<br>
In particular, if you call backward on your model (in any way) all the ops will work with the full batch size of the forward.<br>
Your proposed solution will avoid these extra computations but might not be worth the loss in forward.</p>
<p>You can try them both and see the result. I would be interested to know which one is faster for your usecase?</p>

killamocingbird: <p>I have the exact same question as OP. I tested using torch.diagonal but because I also want to compute the second-order jacobian doing this using diagonal is extremely slow.</p>
<p>Here is the code I’m using</p>
<pre><code class="lang-auto">    def compute_u_x(self, x):
        self.u_x = torch.autograd.functional.jacobian(self, x, create_graph=True)
        self.u_x = torch.diagonal(self.u_x, dim1=0, dim2=2).permute(2, 0, 1)
        return self.u_x
    
    def compute_u_xx(self, x):
        self.u_xx = torch.autograd.functional.jacobian(self.compute_u_x, x)
        self.u_xx = torch.diagonal(self.u_xx, dim1=0, dim2=3).permute(3, 0, 1, 2)
        self.u_xx = torch.diagonal(self.u_xx, dim1=2, dim2=3)
        return self.u_xx
</code></pre>
<p>This will give me what I need, but it’s computing so many extra things it significantly slowed my training loop. I also made a version which isn’t vectorized that uses the torch.autograd.grad function which works exponentially faster than above. However, this method only works for scalar output functions, which is not what I need.</p>

albanD: <p>Computing a Hessian is expected to be slow I’m afraid.<br>
Note that we have a function that computes the hessian directly in some cases that might help. But I don’t expect it to be much faster.</p>
<blockquote>
<p>However, this method only works for scalar output functions</p>
</blockquote>
<p>That’s the trick. If your function has a single input then the full Jacobian is recovered with a single backward pass and all the first order gradients become very easy to compute!</p>

killamocingbird: <p>I was actually able to solve it. This works exponentially faster than using the jacobian and hessian methods + diagonalization. However, I suspect this still isn’t at peak efficiency due to the for-loop. Hopefully something like this can be parallelized and implemented in the future.</p>
<pre><code class="lang-auto"># Creates first and second order jacobian for vector function f
def second_order_jacobians(f, wrt, create_graph=True):
    jacobian_1 = []
    jacobian_2 = []
    for i in range(f.shape[1]):
        j1 = grad(f[:,i:i+1], wrt, create_graph=create_graph, grad_outputs=torch.ones(f[:,i:i+1].shape).to(f.device))[0]
        j2 = grad(j1, wrt, create_graph=create_graph, grad_outputs=torch.ones(j1.shape).to(j1.device))[0]
        jacobian_1.append(j1)
        jacobian_2.append(j2)
    jacobian_1 = torch.stack(jacobian_1, -1)
    jacobian_2 = torch.stack(jacobian_2, -1)
    return jacobian_1, jacobian_2
</code></pre>

albanD: <blockquote>
<p>This works exponentially faster</p>
</blockquote>
<p>You mean just faster right? I don’t see how that could be exponential…</p>
<p>And yes this will work fine as mentioned above. The only downside is that you now do many more forward passes. So depending on your application this will be better or not.</p>

martinsipka: <p>I was facing the same problem as OP and managed to get an elegant workaround using simple <strong>sum</strong> along the batch dimension of the original function. This means the result will be differentiated exactly as OP requested (just write it down). This approach is theoretically <strong>batch_size</strong> times faster than computing full jacobian and then using diagonal. I can see similar speedup in my calculations.</p>
<pre><code class="lang-auto">def batch_jacobian(f, x):
    f_sum = lambda x: torch.sum(f(x), axis=0)
    return jacobian(f_sum, x)
</code></pre>
<p>Note that it is necessary to permute the result to get the <strong>batch_dimension</strong> in front. In OPs case permute(1,0,2) will do the job.</p>
<p>The same trick can be applied for hessian and will bring even more significant speedup.</p>

Youyoun: <aside class="quote no-group" data-username="martinsipka" data-post="7" data-topic="84571">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/martinsipka/48/39780_2.png" class="avatar"> martinsipka:</div>
<blockquote>
<pre><code class="lang-auto">def batch_jacobian(f, x):
    f_sum = lambda x: torch.sum(f(x), axis=0)
    return jacobian(f_sum, x)
</code></pre>
</blockquote>
</aside>
<p>Very nice, didn’t think of it. Yields the exact same results as using a for loop, but runs much faster than the for loop.</p>

caffe_tt: <p>Looks like a very nice workaround, but any explanation on why this can work?</p>
<hr>
<p>Let me try this by myself.</p>
<p>One explanation in my mind is that the change of an instance in batch will  contribute to the change of final sum result <strong>independently</strong>.</p>
<p>Formally,<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/3/9/39bbbf6389f0119b24e9ad9f4ea2d0a2c65c4093.png" data-download-href="https://discuss.pytorch.org/uploads/default/39bbbf6389f0119b24e9ad9f4ea2d0a2c65c4093" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/3/9/39bbbf6389f0119b24e9ad9f4ea2d0a2c65c4093.png" alt="image" data-base62-sha1="8eJsICoHonSYUHzgjd7oyWfxuRt" width="690" height="172" data-dominant-color="EDEDED"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">926×232 8.29 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

mcbal: <p>Indeed, since outputs can’t depend on any other inputs across the batch dimension, all cross-batch entries in the Jacobian are zero. So you’re still doing all the useless computations but now without a for-loop.</p>
<p>As mentioned above, the functional API works at the autograd level and so is not aware of things like batch size. You can think about this trick as working around this limitation by turning the batch of outputs into a sum of contributions and the batch of inputs into a single big example. Along the batch dimension, only the matching outputs and inputs will contribute a non-zero result.</p>
<p>Explicitly, for batches of input vectors getting transformed into batches of output vectors, the trick sums the outputs <code>(batch_size, out)</code> into <code>(out)</code> so that taking the derivative with respect to the “single big example” <code>(batch_size, in)</code> outputs a Jacobian with shape <code>(out, batch_size, in)</code>. Permuting then gives you the Jacobian you want.</p>

martinsipka: <p><a class="mention" href="/u/mcbal">@mcbal</a> Yes exactly. Although I do not agree with the statement</p>
<aside class="quote no-group" data-username="mcbal" data-post="10" data-topic="84571">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mcbal/48/47449_2.png" class="avatar"> mcbal:</div>
<blockquote>
<p>So you’re still doing all the useless computations</p>
</blockquote>
</aside>
<p>I do not really see the reason why the this would be the case. The test also indicate that this does not happen and the computation is much faster. Am I mistaken <a class="mention" href="/u/mcbal">@mcbal</a> ?</p>

mcbal: <p><a class="mention" href="/u/martinsipka">@martinsipka</a> I could be wrong here, but I was under the impression that the speedup came from the parallelisation enabled by acting on the result of the sum across batches. The “batch-off-diagonal” terms are still present, but since the derivative across batches is zero they don’t yield a contribution to the sum. Here is a small code snippet to illustrate what I mean:</p>
<pre><code class="lang-auto">import torch
from torch import autograd, nn

bsz, dim_in, dim_out = 3, 5, 7

x = torch.randn(bsz, dim_in)
f = nn.Linear(dim_in, dim_out)

@torch.enable_grad()
def batch_jacobian(f, x):
    f_sum = lambda x: torch.sum(f(x), axis=0)
    return autograd.functional.jacobian(f_sum, x).swapaxes(1, 0)

print(batch_jacobian(f, x))

@torch.enable_grad()
def batch_jacobian_take_zeroth_output(f, x):
    f_sum = lambda x: f(x)[0]
    return autograd.functional.jacobian(f_sum, x).swapaxes(1, 0)

print(batch_jacobian_take_zeroth_output(f, x))
</code></pre>
<p>In this example, the first <code>print</code> statement returns the “batch-diagonal” Jacobian entries corresponding to (<code>00</code>, <code>11</code>, <code>22</code>), just like the snippet you posted earlier in this thread. The second <code>print</code> statement restricts the output to the zeroth element in the batch so that computing the Jacobian with respect to the full batch now includes some “batch-off-diagonal” entries (<code>00</code>, <code>01</code>, <code>02</code>). Only the zeroth element (<code>00</code>) in the batch contains non-zero entries, the other “batch-off-diagonal” entries (<code>01</code>, <code>02</code>) are zero.</p>