<h2 dir="auto">❓ Questions and Help</h2>
<p dir="auto">Under PyTorch's no gradient mode, any tensor returned by operations shouldn't create a new or extend an existing computation graph (i.e. <code class="notranslate">requires_grad</code> should be false and <code class="notranslate">grad_fn</code> should be <code class="notranslate">None</code>). However, when using <code class="notranslate">Tensor.expand</code> this is clearly not the case. Consider the following code:</p>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="a = torch.tensor(1., requires_grad=True)
b = a.clone()
with th.no_grad():
    c = b.expand((1,))

c.requires_grad # True"><pre class="notranslate"><span class="pl-s1">a</span> <span class="pl-c1">=</span> <span class="pl-s1">torch</span>.<span class="pl-en">tensor</span>(<span class="pl-c1">1.</span>, <span class="pl-s1">requires_grad</span><span class="pl-c1">=</span><span class="pl-c1">True</span>)
<span class="pl-s1">b</span> <span class="pl-c1">=</span> <span class="pl-s1">a</span>.<span class="pl-en">clone</span>()
<span class="pl-k">with</span> <span class="pl-s1">th</span>.<span class="pl-en">no_grad</span>():
    <span class="pl-s1">c</span> <span class="pl-c1">=</span> <span class="pl-s1">b</span>.<span class="pl-en">expand</span>((<span class="pl-c1">1</span>,))

<span class="pl-s1">c</span>.<span class="pl-s1">requires_grad</span> <span class="pl-c"># True</span></pre></div>
<p dir="auto">Although variable <code class="notranslate">c</code> is not attached to the computation graph that contains <code class="notranslate">a</code> and <code class="notranslate">b</code>, <code class="notranslate">c</code> has its <code class="notranslate">requires_grad</code> property set to <code class="notranslate">True</code> which will create a new computation graph. Is this the expected behavior or is this a bug?</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="&gt;&gt;&gt; x = torch.randn(3, requires_grad=True)
&gt;&gt;&gt; with torch.no_grad():
...   print(x[1])
...
tensor(-0.0967, requires_grad=True)"><pre class="notranslate"><code class="notranslate">&gt;&gt;&gt; x = torch.randn(3, requires_grad=True)
&gt;&gt;&gt; with torch.no_grad():
...   print(x[1])
...
tensor(-0.0967, requires_grad=True)
</code></pre></div>