Per-sample gradient, should we design each layer differently?

Konpat_Ta_Preechakul: <p>There are some applications requiring per-sample gradient (not a mini-batch gradient). Let’s say we need it.</p>
<p>There is a few ways to do it with autograd:</p>
<ol>
<li>Call it many times, each for a single loss in a mini-batch. This is slow.</li>
<li>Using Goodfellow’s method <a href="http://arxiv.org/abs/1510.01799" rel="nofollow noopener">http://arxiv.org/abs/1510.01799</a> which is basically multiplying the hidden state’s gradients with the input to the layer to complete the gradient.</li>
</ol>
<p>The idea of 2) is efficient because we do only necessary computation, however we need to manually code the derivative of the output of a layer wrt. its weights for each layer manually (autograd will not do that step for us).</p>
<p>There is a way to allow for autograd end-to-end which is to design the layer “a bit differently”.</p>
<p>The problem with the current design of a layer and per-sample gradient is that the weight is “shared” among samples within a mini-batch. Had it not shared, we can compute gradient wrt. each weights for each sample. This is equivalent to the Goodfellow’s method computation-wise.</p>
<p><strong>Example for a linear layer:</strong></p>
<p>Traditionally we define a linear layer:</p>
<pre><code class="lang-auto">x (batch, features)
w (in_features, out_features)
torch.einsum('ni,ij-&gt;nj', x, w)
</code></pre>
<p>A revised version would be:</p>
<pre><code class="lang-auto">x (batch, features)
w (in_features, out_features)
ww = w.expand(batch, in_features, out_features)
ww.retain_grad()
y = torch.einsum('ni,nij-&gt;nj', x, ww)
</code></pre>
<p>We will now get the gradient <code>ww.grad</code> which has the shape (batch, in_features, out_features), per-sample gradient.</p>
<p><strong>Questions</strong></p>
<ul>
<li>
<strong>Memory footprint is about the same</strong> as mini-batch gradient except for the storage for the per-sample gradient for each weights, is it not?</li>
<li>
<strong>Computation-wise they would be the same</strong> as mini-batch gradient, we just save ourselves the last sum-reduction step?</li>
<li>Are there any roadblocks in terms of implementation such that it would be much less efficient memory-wise or computation-wise?</li>
</ul>

albanD: <p>Hi,</p>
<p>The main roadblock to introduce this in the core library is that even though this works for some layers, it cannot be generalized easily to all operations supported by the autograd.</p>
<p>If you use these operations though, <a href="https://github.com/cybertronai/autograd-hacks#per-example-gradients" rel="nofollow noopener">this</a> package by <a class="mention" href="/u/yaroslav_bulatov">@Yaroslav_Bulatov</a> is what I would use.</p>

Yaroslav_Bulatov: <p>Per-example and mean-gradient calculations work on the same set of inputs, so PyTorch autograd already gets you 90% of the way there. For an illustration: consider the problem of backprop in a simple feedforward architecture.</p>
<p>Each layer has a Jacobian matrix and we get the derivative by multiplying them out.</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/3X/f/1/f10a3ff1758fa265eb6222a9349c471d5d352813.png" alt="image" data-base62-sha1="yol1SXvjPtIcGAUFEBDD1M1JHB9" width="602" height="483"></p>
<p>While any order of matrix multiplication is valid, reverse differentiation specializes to multiplying them “left to right”.</p>
<p>For “left-to-right” order, each op implements “vector-Jacobian” product, called “backward” in PyTorch, “grad” in TensorFlow and “Lop” in Theano. This is done without forming Jacobian matrix explicitly, necessary for large scale applications.</p>
<p>When dealing with non-linear functions, each example in a batch corresponds to a different Jacobian, so our backward functions do this in a batch fashion.</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/6/8/68624e99e84fc35c9f890029fb7de392a0333f4e.png" data-download-href="https://discuss.pytorch.org/uploads/default/68624e99e84fc35c9f890029fb7de392a0333f4e" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/6/8/68624e99e84fc35c9f890029fb7de392a0333f4e.png" alt="image" data-base62-sha1="eTqhhD2q1GjXQEcmMGAjZhM14nk" width="690" height="167" data-dominant-color="CFCFCF"><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">707×172 10.5 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>
<p>Autograd engine traverses the graph and feeds a batch of these vectors (backprops) into each op to obtain backprops for the downstream op.</p>
<p>To see how per-example calculation works, note that for matmul, parameter gradient is equivalent to computing a batch of outer products of matching activation/backprop vector pairs, then summing over the batch dimension. Activations are values fed into the layer during forward pass.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/c/5/c5eb956628c7ee61b487921259d4b2c526b87ead.png" data-download-href="https://discuss.pytorch.org/uploads/default/c5eb956628c7ee61b487921259d4b2c526b87ead" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/c/5/c5eb956628c7ee61b487921259d4b2c526b87ead_2_690x140.png" alt="image" data-base62-sha1="seSNqpgAF2Yjs2uS9w6BfAomuaV" width="690" height="140" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/c/5/c5eb956628c7ee61b487921259d4b2c526b87ead_2_690x140.png, https://discuss.pytorch.org/uploads/default/original/3X/c/5/c5eb956628c7ee61b487921259d4b2c526b87ead.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/c/5/c5eb956628c7ee61b487921259d4b2c526b87ead.png 2x" data-dominant-color="D3CECF"><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">1034×210 20.8 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>
<p>We get the per-example gradients by dropping the sum<br>
<img src="https://discuss.pytorch.org/uploads/default/original/3X/b/2/b20e7692d830da09dee947a1b592ef1b3caf64c4.png" alt="image" data-base62-sha1="pp9Yzq1LDU9JGN78EqHcT7tJ8dS" width="652" height="234"></p>
<p>Basically it’s a matter of replacing<br>
<code>grad=torch.einsum('ni,nj-&gt;ij', backprops, activations)</code><br>
with<br>
<code>grad1=torch.einsum('ni,nj-&gt;nij', backprops, activations)</code></p>
<p>Because grad1 calculation doesn’t affect downstream tasks, you only need to implement this for layers that have parameters. The <a href="https://github.com/cybertronai/autograd-hacks" rel="noopener nofollow ugc">autograd-hacks</a> lib does this for Conv2d and Linear. To extend to a new layer, you would look for the “leaf” ops, look at their  “backwards” implementation and figure out how to drop the “sum over batch” part.</p>

Konpat_Ta_Preechakul: <p>I have been using your library, and I’m thankful for that. It is still the case that some layers are not trivial to implement the derivative. I’m thinking of the likes of LSTM.</p>
<p>My proposed implementation should match yours (which is derived from Goodfellow’s) for all steps of activations. Our methods only differ at the last steps where yours needs to code the derivative while mine doesn’t need that.</p>
<p><a class="mention" href="/u/alband">@albanD</a> Could you elaborate a bit more on the roadblocks you mentioned? Anyway, could you comment on the memory footprint and computation requirement as well?</p>

Yaroslav_Bulatov: <p>I looked at your example more carefully and expand seems like a neat trick.</p>
<p>It’s simpler, and avoids capturing an extra reference to activations like I do in autograd_hacks.<br>
But extra memory usage means you can’t make this the default – big models are already memory bottlenecked and gradients are large. IE, GPT-2 gradient is 6GB per example.</p>

albanD: <p>I don’t remember, but I don’t think convolution ops accept expanded weight, <a class="mention" href="/u/konpat_ta_preechakul">@Konpat_Ta_Preechakul</a> ?</p>
<p>As we discussed with Yaroslav before. The roadblock is that this accumulation is a property of the op you are doing, not of the autograd. You could be doing many operations on your weights before passing it to the Linear layer (for example people that enforce some structure on weights). In that case, it’s not only the last layer for which you need this special function, but for all the layers before this one.</p>

Konpat_Ta_Preechakul: <p>Don’t be annoyed yet. I still can’t see why convolution would not be compatible with expanded weight. Current implementation sure it might not. The proposal very likely requires re-implementation of all layers anyway.</p>

Yaroslav_Bulatov: <p>The “per-example gradient” computation needs to distinguish between “data” and “parameter” inputs, so it’s natural to handle them at the level of layers (ie, subclasses of nn.Module) rather than at the level of ops.</p>
<p>A practical limitation is that PyTorch ops often don’t support batch dimension for the weight input. For example, <a href="https://arxiv.org/abs/1906.02506" rel="nofollow noopener">https://arxiv.org/abs/1906.02506</a> needed to compute loss over a batch of weights in PyTorch. The solution had to use 8 copies of model for a batch of size 8 (one per GPU).</p>

Konpat_Ta_Preechakul: <blockquote>
<p>“per-example gradient” computation needs to distinguish between “data” and “parameter” inputs</p>
</blockquote>
<p>Why is that the case?</p>
<blockquote>
<p>A practical limitation is that PyTorch ops often don’t support batch dimension for the weight input.</p>
</blockquote>
<p>This limitation doesn’t seem like a roadblock. It seems like something that a re-implementation could solve.</p>

Yaroslav_Bulatov: <p>So that you know which Tensors to call “expand” on <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"><br>
In other words, this doesn’t need to change the autograd engine, just the layer implementations.</p>
<p>Changing all layers to do this by default would break things because of extra memory usage. But you could create custom layers that extend existing layer with “per-example-gradient-capturing” behavior using the expand trick.</p>
<p>Adding for Conv2d weight batching seems like a generally useful feature to have.  “groups” feature already implements something similar because each group has its own set of filters.</p>

albanD: <p>I agree with you. There is nothing theoretical preventing us from doing it.<br>
I said it was a roadblock in the sense that it will be time consuming to implement and unlikely to be high priority enough to be done now by the core team.</p>
<p>That being said, we will be very happy to accept a PR that adds support for weights that have an extra dimension for the batch size.<br>
If you do have time to work on this, you can open an issue that explains how you plan to add this and I will be more than happy to help have a good design for this and then review the implementation !</p>
<p>The tricky parts/questions that need answering are:<br>
backend:</p>
<ul>
<li>Fast conv for weights with an extra batch dimension. like mm/bmm, have conv/bconv</li>
<li>Check other commonly used Module (like batchnorm) to make sure the underlying implementation will support batched weights</li>
</ul>
<p>frontend:</p>
<ul>
<li>Do you need the ability to switch between the two modes?</li>
<li>Do we want this to be built in existing <code>nn.Module</code>s? (if so, how do we handle possibly changing batch-sizes)</li>
<li>Do we want element-wise versions of the existing modules as new Modules?</li>
</ul>

Konpat_Ta_Preechakul: <p>Based on your intuitions, do you think it would be theoretically slower? For example, this batched weights might prevent low-level optimization of some kind. I have no experience in low-level GPU programming. <img src="https://discuss.pytorch.org/images/emoji/apple/sweat.png?v=9" title=":sweat:" class="emoji" alt=":sweat:"></p>

albanD: <p>Well you could play tricks and if you detect that the weights are indeed only <code>expanded</code>, you can use the original forward and so not have any performance loss.<br>
For both the case where the weights are actually different and for the backward, I have to admit I don’t know. But there will be some performance drop because you won’t be able to use the cudnn optimized kernels I’m afraid.</p>
<p>That being said, it is expected to be more expensive to compute element-wise gradients in most cases.</p>

Yaroslav_Bulatov: <p>Replacing single matmul with 2 einsums could be slower because of difference in speeds in GPU memory types. You have fast SRAM used for intermediate results and slow GPU memory for main storage. For low arithmetic intensity operations on V100, HBM2 can’t keep up with the compute units and becomes the bottleneck. For instance, you can’t do “torch.einsum(‘ni,nij-&gt;nj’, x, ww)” at nearly the same FLOPS as regular matmul or conv.</p>

Konpat_Ta_Preechakul: <p>That is precisely what I saw!</p>

AlphaBetaGamma96: <p>Hi everyone, and sorry for opening a topic which is over 2 years old.</p>
<p>I was wondering if I could ask a quick question about what precisely the per-sample gradient is here?</p>
<p>What I exactly mean by this is you’re converting the gradient of the layer to get the gradient for all samples by using the <code>grad_output</code> and <code>activations</code> of a given layer, and using <code>torch.einsum</code> to combine the two.</p>
<p>But, I’m not 100% sure what exactly the per-sample gradient is. To illustrate my point, let’s assume I have a set of inputs of shape <code>[B, A]</code> where <code>B</code> is the batch size, and <code>A</code>  is the number of inputs. (For example with a simple Feed-Forward Network). Where I would pass these inputs through a loss function (containing a network of parameters) which returns a Tensor of shape <code>[B,]</code> (where each element of this Tensor is effectively an individual loss for each sample in the batch).</p>
<p>If I define the (total) loss as the mean of these individual loss values (so, reduce the Tensor of shape <code>[B,]</code> to a scalar), and backprop that loss via <code>loss.backward()</code>  while using the hooks (as mentioned above) to get the gradients of the parameters for all samples.</p>
<p>Would these gradients be <em>either</em>,</p>
<ol>
<li>
<p>the gradient of the (total) loss w.r.t the parameters for the i-th sample within the batch for all samples</p>
</li>
<li>
<p>the gradient of the individual loss of the i-th sample w.r.t the parameters for all samples</p>
</li>
</ol>
<p>The only reason why I’m asking for this clarification is that I’m trying to get the 2nd case here where I can calculate the gradient of the individual loss values w.r.t the parameters of a <code>nn.Module</code> for all samples.</p>
<p>An example use case would be the KFAC optimizer where you need to compute the exact-fisher for all samples when rescaling your preconditioned gradients.</p>
<p>I’ve managed to make an example code comparing the 2 methods,</p>
<ol>
<li>
<p>using hooks to get the gradient of the (total) loss of the i-th sample for all samples (in a similar way to autograd-hacks)</p>
</li>
<li>
<p>iterate over the batch and compute the gradient of the individual loss w.r.t the parameter for each sample sequentially and store within a list, which is subsequently stacked to get the same shape as the Tensor returned via the hooks method (which is incredibly slow).</p>
</li>
</ol>
<p>Both these methods return different values which would indicate 2 things. Either I’ve possibly made a mistake somewhere in my code or the gradients returned via the hooks is the grad of the total-loss w.r.t parameters for all samples rather than the grad of the individual losses w.r.t the parameters. I should note all my samples are independent of each other when passed through the loss function!</p>
<p>Apologizes for the long reply for a 2-year-old post but as this isn’t really mentioned within the docs I’d just like to clarify some points!</p>
<p>Any help would be greatly appreciated!</p>
<p>Thank you for your time,<br>
Kind regards!</p>
<p><strong>TL;DR</strong> - Are the gradients for all samples which are calculated via this autograd-hacks method the gradient of the total loss with respect to the parameters for all samples or the gradient of each individual loss with respect to the parameters for all samples? (where individual loss means, the loss of a single sample before its reduction to a scalar loss. So, a batch of B samples would have B individual losses.)</p>
<p>Thanks once again! <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=10" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

Yaroslav_Bulatov: <p>A batch of size k with k per-example gradients is numerically equivalent to iterating over k examples using batch size 1 and saving k gradients you get.</p>
<p>This mini-unit test in the docs of autograd-hacks should additionally clarify the relationship between per-example gradients and the “gradient”</p>
<pre><code class="lang-auto"># param.grad: gradient averaged over the batch
# param.grad1[i]: gradient with respect to example i

for param in model.parameters():
  assert(torch.allclose(param.grad1.mean(dim=0), param.grad))
</code></pre>
<p>Note that KFAC implementations typically inject isotropic random vectors at the output layer (ie, call <code>output.backward(random_vec)</code>) and compute factored approximation of resulting covariance matrix of gradients. This (in expectation) is equal to Gauss-Newton matrix, with softmax loss replaced by least-squares loss, rather than Fisher matrix.</p>
<p>Problem with Fisher matrix (and Gauss-Newton with softmax) is that once you start converging, those two matrices go to zero, so preconditioning by such matrix is a division by zero.</p>
<p>I have an example of computing KFAC factors in a slightly cleaned-up autograd-lib here:</p><aside class="onebox allowlistedgeneric" data-onebox-src="https://github.com/cybertronai/autograd-lib#example-2-hessian-quantities">
  <header class="source">
      <img src="https://github.githubassets.com/favicons/favicon.svg" class="site-icon" width="32" height="32">

      <a href="https://github.com/cybertronai/autograd-lib#example-2-hessian-quantities" target="_blank" rel="noopener nofollow ugc">GitHub</a>
  </header>

  <article class="onebox-body">
    <div class="aspect-image" style="--aspect-ratio:690/345;"><img src="https://opengraph.githubassets.com/3f3bc6d3ecf5c06e40228b43dc0301148c206b951bdc14f1c7372c5d4f92271f/cybertronai/autograd-lib" class="thumbnail" width="690" height="345"></div>

<h3><a href="https://github.com/cybertronai/autograd-lib#example-2-hessian-quantities" target="_blank" rel="noopener nofollow ugc">GitHub - cybertronai/autograd-lib</a></h3>

  <p>Contribute to cybertronai/autograd-lib development by creating an account on GitHub.</p>


  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>


AlphaBetaGamma96: <p>Hi <a class="mention" href="/u/yaroslav_bulatov">@Yaroslav_Bulatov</a>!</p>
<p>Thank you for the very quick and detailed response!</p>
<p>I assume the reason behind why they’re equivalent is because the gradient of mean(L_i) w.r.t parameter_j  is equal to the gradient of mean(L_i) w.r.t L_i’ * gradient L_i’ w.r.t parameter_j and the first gradient term is just 1, so they’re equivalent?  (I assume this only works for independent samples?)</p>
<p>Thank you for the explanation between per-sample gradient and “gradient”, I think I fully understand it now!</p>
<p>The follow-up question I would have, if that’s ok, is when I did an example script for my problem I got <code>grad1.mean(dim=0)</code> to equal <code>param.grad</code>. Which would show my own method is correct, right?</p>
<p>However, if I iterate through all my data sequentially and calculate an individual loss, and gradients via <code>loss_i.backward()</code> and store <code>model.parameters.grad()</code> within a list (with also calling <code>model.zero_grad()</code> between samples so grads don’t accumulate) I don’t get the same values as those returned via the hooks. So, I’m somewhat confused as to why they’re different.</p>
<p>Are there any caveats to using hooks for this? To give a bit more detail about my loss function it does contain a Laplacian operator, so calculates the Trace of the Hessian matrix of the output of my network w.r.t the inputs. Could this be a potential issue? Perhaps maybe the <code>grad_output</code> term is from the Laplacian rather than the loss function itself? Thereby explaining any potential difference between the sequential method and the batch method?</p>
<p>If it’s not too much could I post an example to illustrate my particular problem?</p>
<p>Thank you for your time!</p>

Yaroslav_Bulatov: <p>They should be the same. To debug, just take an example small enough to calculate the gradients by hand and compare against what you are seeing.</p>
<p>For instance, y=wx, set your w=1, and loss y^2/2. Then your gradient is the same as x. Here’s an example of computing two gradient for two different x’s and checking that they match manually computed gradient – <a href="https://colab.research.google.com/drive/10h-3sZzipw8tmzNTZf8Uewyyt6hFUVB7?usp=sharing" class="inline-onebox" rel="noopener nofollow ugc">Google Colab</a></p>
<p>You can use this to debug your Hessian trace as well, trace is especially easy when everything is a scalar</p>

AlphaBetaGamma96: <p>Hi <a class="mention" href="/u/yaroslav_bulatov">@Yaroslav_Bulatov</a>!</p>
<aside class="quote no-group" data-username="Yaroslav_Bulatov" data-post="20" data-topic="57293">
<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/yaroslav_bulatov/48/7017_2.png" class="avatar"> Yaroslav_Bulatov:</div>
<blockquote>
<p>They should be the same. To debug, just take an example small enough to calculate the gradients by hand and compare against what you are seeing.</p>
</blockquote>
</aside>
<p>I’ve managed to create a “relatively” simple example to get the per-sample gradient for the output of my network w.r.t the network’s parameters for all samples and they match with the sequential per-sample method. So, that’s working.</p>
<p>I’m trying to derive it for another loss function which contains the Laplacian, the way in which I calculate the Laplacian is via using the trick shown <a href="https://discuss.pytorch.org/t/how-to-calculate-laplacian-sum-of-2nd-derivatives-in-one-step/41667/3">here</a>. This trick allows you to calculate the Laplacian with batch-support whereas doing it via <code>torch.autograd.functional.hessian</code> which only supports 1 example per call.</p>
<p>As I store the <code>grad_output</code> within a dictionary with the key <code>['e']</code> every time I call <code>torch.autograd.grad</code> (which happens N+1 times for an NxN Hessian matrix) it’ll overwrite the <code>grad_output</code> for each layer with the final component of the laplacian as opposed to the entire laplacian itself. Is this method (as shown <a href="https://discuss.pytorch.org/t/how-to-calculate-laplacian-sum-of-2nd-derivatives-in-one-step/41667/3">here</a>) compatible with getting a per-sample gradient via hooks if the per-sample gradients depend on other derivative information as well, which with the code in the link is the laplacian of the output of the network w.r.t the input! (If this makes sense?)</p>
<p>thank you for your help! <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<p>p.s. is it possible to share the colab example document publicly? (i.e. without requesting access?)</p>