My model gets worse when I use einsum?

miturian: <p>I have two versions of my network. The original version contains this (it’s simplified slightly for ease of reading):</p>
<pre><code class="lang-auto">nChan=1
nFilter=3
timeBins=4
nFreq=5

#setup:
L = nn.Parameter(torch.randn(nFreq,nFilter),requires_grad=False)
E = nn.Parameter(torch.randn(nFilter,nChan))

#forward():
F = torch.multiply(torch.sigmoid(E[:,0]),L)
x1 = torch.matmul(x[:,:,:,0], F)
</code></pre>
<p>The ‘improved’ version has the two forward steps merged into one:</p>
<pre><code class="lang-auto">x=torch.einsum('btrc,ri,ic-&gt;btic',x,L,torch.sigmoid(E))
</code></pre>
<p>Running the two versions on the same input gives the same result (up to float precision):</p>
<pre><code class="lang-auto">x0=torch.randn(10,timeBins,nFreq,1)
x=x0
F = torch.multiply(torch.sigmoid(E[:,0]),L)
x1 = torch.matmul(x[:,:,:,0], F) # filtering
x1 = torch.reshape(x1, [-1, timeBins, nFilter])       

x=x0
x=torch.einsum('btrc,ri,ic-&gt;btic',x,L,torch.sigmoid(E))
x2=torch.reshape(x,(-1,timeBins,nFilter*nChan))
print(x1-x2)
</code></pre>
<blockquote>
<p>tensor([[[ 0.0000e+00,  0.0000e+00,  2.9802e-08],<br>
[ 1.1921e-07,  2.9802e-08, -5.9605e-08],<br>
[ 5.9605e-08, -1.1921e-07,  0.0000e+00],<br>
[ 0.0000e+00, -1.1921e-07, -2.9802e-08]],</p>
<pre><code>    [[-7.4506e-09,  0.0000e+00,  0.0000e+00],
     [ 0.0000e+00,  0.0000e+00, -3.7253e-08],
     [-2.9802e-08, -5.9605e-08,  5.9605e-08],
     [ 0.0000e+00, -5.9605e-08, -5.9605e-08]],

    [[ 0.0000e+00,  0.0000e+00,  0.0000e+00],
     [-2.9802e-08, -1.4901e-08,  2.9802e-08],
     [ 0.0000e+00, -1.1921e-07,  5.9605e-08],
     [ 0.0000e+00,  1.1921e-07, -1.1921e-07]],

    [[ 0.0000e+00, -5.9605e-08, -2.3842e-07],
     [ 0.0000e+00,  2.9802e-08, -2.3842e-07],
     [ 0.0000e+00, -1.4901e-08,  0.0000e+00],
     [ 0.0000e+00,  2.3842e-07, -1.1921e-07]],

    [[ 2.3842e-07,  3.7253e-08, -4.7684e-07],
     [-1.1176e-08,  0.0000e+00, -1.1921e-07],
     [ 0.0000e+00, -5.9605e-08, -1.7881e-07],
     [-2.9802e-08,  5.9605e-08,  0.0000e+00]],

    [[-5.9605e-08, -7.4506e-09, -1.1921e-07],
     [ 0.0000e+00,  0.0000e+00,  1.1921e-07],
     [ 5.9605e-08,  5.9605e-08, -2.9802e-08],
     [-2.9802e-08,  5.9605e-08, -1.1921e-07]],

    [[-2.9802e-08,  2.9802e-08,  0.0000e+00],
     [ 5.9605e-08,  2.3842e-07,  5.9605e-08],
     [-2.2352e-08,  0.0000e+00,  0.0000e+00],
     [ 0.0000e+00,  2.9802e-08,  5.9605e-08]],

    [[ 0.0000e+00, -1.4901e-08,  0.0000e+00],
     [-5.9605e-08,  0.0000e+00, -8.8476e-09],
     [ 0.0000e+00,  0.0000e+00,  1.4901e-08],
     [ 7.4506e-09, -5.9605e-08,  0.0000e+00]],

    [[ 0.0000e+00,  0.0000e+00, -2.3842e-07],
     [-1.1921e-07, -1.1921e-07,  0.0000e+00],
     [ 2.0023e-08,  0.0000e+00, -1.2547e-07],
     [ 0.0000e+00, -2.2352e-08, -5.9605e-08]],

    [[ 1.4901e-08,  5.9605e-08, -1.1921e-07],
     [ 0.0000e+00,  0.0000e+00,  7.4506e-09],
     [ 0.0000e+00,  2.3842e-07,  5.9605e-08],
     [-5.9605e-08,  2.2352e-08,  0.0000e+00]]], grad_fn=&lt;SubBackward0&gt;)
</code></pre>
</blockquote>
<p>If I change datatypes to double everywhere, the errors move down to e-16.</p>
<p>However, after making this change,  my performance has decreased by around 2%. On the specific problem I am working on, this is the difference between being ‘state of the art’ and ‘OK’. I have tried running both versions with a range of different seeds, learning rates etc., and it is very clear that the einsum version hits a ceiling a few percentage points below that of the original version.</p>
<p>If it makes a difference, I am happy to share the ‘derivation’ for why this is the correct einsum expression, if the size of the differences is not convincing enough.</p>
<p>What could be going on?</p>

tom: <p>PyTorch’s einsum - in contrast to numpy’s - isn’t optimized for speed but breaks down the einsum into things that are ultimately (batched) matrix multiplications. The idea I had in mind when implementing it was that is was a mere convenience thing. This turned out to be wrong, but no-one stepped up to provide a genuinely faster reimplementation yet although some cases were identified where the batched matrix multiplication could be replaced by eg a plain matmul. (I did experiment with a different reduction kernel, but it seemed to be faster on some, slower on other inputs, not least because it is actually hard to match matrix multiplication routines shipped in the vendor libraries.)</p>
<p>So your observation is quite plausible.</p>
<p>Best regards</p>
<p>Thomas</p>

miturian: <p>sorry, I think I have expressed myself poorly.</p>
<p>I do not mean that the calculation is slower. In fact einsum is faster (around 25% on average, I believe). My problem is that on average, the accuracy of my predictions (it’s a classification task), is slightly worse.</p>

miturian: <p>so, I get different outputs, and on average, those different outputs are slightly more wrong than what the original version returns.<br>
is it possible that the gradient is calculated slightly differently, or some such thing?</p>

tom: <p>Oh, sorry, I didn’t get that right.<br>
Well, so the gradient would also be subject to numerical accuracy differences similar to those in the forward. If you want to be certain, you could extend your test program to run <code>torch.autograd.gradcheck</code>.<br>
Those are legitimate and, unfortunate as it is, it would seem that the model training is quite brittle (which is the case in deep learning more often than it should).</p>
<p>Best regards</p>
<p>Thomas</p>

miturian: <p>Hi again <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"><br>
Is this what you suggest?</p>
<pre><code class="lang-auto">def func1(x,E,L):
    F = torch.multiply(torch.sigmoid(E[:,0]),L)
    return torch.matmul(x[:,:,:,0], F)

def func2(x,E,L):
    return torch.einsum('btrc,ri,ic-&gt;btic',x,L,torch.sigmoid(E))

torch.autograd.gradcheck(func1,(x0,E,L))

torch.autograd.gradcheck(func2,(x0,E,L))
</code></pre>
<p>I have changed the precisions to double for everything, and it seems that at least according to the standard settings, both versions have the correct gradients. I have also tried to change atol and rtol, but can not seem to find values where one fails but not the other.</p>
<p>This is a bit annoying. both because I adore the idea of einsum (my background is in physics), and because it gives a very nice way of generalizing my code beyond nChan=1.</p>
<p>it seems that for now, I should just stay away from einsum?</p>

tom: <aside class="quote no-group" data-username="miturian" data-post="6" data-topic="120695">
<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/miturian/48/34819_2.png" class="avatar"> miturian:</div>
<blockquote>
<p>it seems that for now, I should just stay away from einsum?</p>
</blockquote>
</aside>
<p>You do whatever keeps PyTorch most useful for you. But beware: The different implementations of matmul can and will have numerical precision differences, too.<br>
The mathematician in me is convinced that we’ll eventually have more robust procedures, but clearly we aren’t there yet.</p>
<p>Best regards</p>
<p>Thomas</p>