MatMul for Slice behaves inconsistently on Tensors of different sizes, causing calculation graph damage

betacat2048: <p>When I execute the following code, there is no error:</p>
<pre><code class="lang-auto">A = torch.eye(3, 3, requires_grad=True)
y = torch.randn(5, 2, 3, 3)

y[:, 1, :, :] = y[:, 0, :, :] @ A
y.sum().backward()
</code></pre>
<p>But if you make a slight modification: change the size of the first dimension from 5 to 1, an error occurs.</p>
<pre><code class="lang-auto">A = torch.eye(3, 3, requires_grad=True)
y = torch.randn(1, 2, 3, 3)

y[:, 1, :, :] = y[:, 0, :, :] @ A
y.mean().backward()
</code></pre>
<p>The error is:</p>
<pre><code class="lang-auto">RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [3, 3]], which is output 0 of AsStridedBackward0, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
</code></pre>
<p><strong>My current version is ‘2.0.0+cu118’; I also tested ‘1.13.0+cu117’ the error still exists. (I didn’t test other versions, so not sure about other versions)</strong></p>
<p>It seems that when the first dimension is 1, the in-place operation will be automatically performed when the slice is assigned, which will cause the calculation graph to be destroyed.</p>
<p>A simple solution is to manually <code>clone()</code>, as follows:</p>
<pre><code class="lang-auto">A = torch.eye(3, 3, requires_grad=True)
y = torch.randn(1, 2, 3, 3)

y[:, 1, :, :] = y[:, 0, :, :].clone() @ A
y.mean().backward()
</code></pre>
<p>I’m wondering, are there any more details about Slice assignment mentioned in the documentation?<br>
Is this situation I encountered intentional for performance optimization, or is it a BUG?</p>

soulitzer: <p>This is expected behavior. The original tensor needs to be saved for backward, so if you slice assign into it, when that tensor is used for gradient computation later it wouldn’t be computing the right thing. The error is there to prevent that.</p>

KFrank: <p>Hi Soulitzer!</p>
<aside class="quote no-group" data-username="soulitzer" data-post="2" data-topic="178946" data-full="true">
<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/s/839c29/48.png" class="avatar"> soulitzer:</div>
<blockquote>
<p>This is expected behavior.</p>
</blockquote>
</aside>
<p>But why does it work when the first dimension of the <code>y</code> tensor has size 5, but<br>
not when it has size 1?  I don’t have any good theories as to why the two cases<br>
behave differently.</p>
<p>Best.</p>
<p>K. Frank</p>

betacat2048: <p>First of all, I know that the calculation graph needs to retain the original tensor for backward, but here <code>y[:, 1, :, :] = y[:, 0, :, :] @ A</code>, the first two slices for assignment The two dimensions are different (one is 1, and the other is 0), this should not destroy the original tensor.</p>
<p>Second, this doesn’t explain why it doesn’t generate an error when the size of the first dimension is not 1.</p>
<p>I guess this may be due to the extra clone introduced by the slice view when the first dimension is not 1, or for performance, it will automatically perform in-place calculations when there are dimensions that can be squeezed? But I didn’t find related documentation.</p>
<p>PS: Is there any documentation on slice specifics? I searched for “pytorch slice” and “slice assign” but couldn’t find the corresponding documentation.</p>

soulitzer: <p><a class="mention" href="/u/kfrank">@KFrank</a> <a class="mention" href="/u/betacat2048">@betacat2048</a></p>
<p>Whoops didn’t read the post fully the first time - The difference is probably because in the “first dimension is not 1” because matmul needs to do some extra reshaping to preprocess the inputs. And depending on the shape/strides of the tensor to reshape “reshape” may or may not call clone underneath.</p>

betacat2048: <p>I think your guess is right, the problem seems to be related to MatMul, because if you change <code>@</code> to <code>+</code>, no Error will be raise.<br>
It seems that MatMul will have different behaviors for different Slices, but it doesn’t seem to be mentioned in the documentation (<a href="https://pytorch.org/docs/stable/generated/torch.matmul.html" rel="noopener nofollow ugc">torch.matmul</a>). Is there any other documentation that explains the error?</p>

soulitzer: <p>Doing + doesn’t raise because to compute its derivative does not require saving the inputs. What is saved as input/output is considered implementation detail, so not documented unfortunately.</p>