Tensor to Variable and memory freeing best practices

rwightman: <p>So, fairly typical sequence in many PyTorch training/optimization or evaluation loops:</p>
<ol>
<li>Create and initialize a Tensor</li>
<li>Transfer (maybe) to GPU</li>
<li>Initialize a Variable with this Tensor</li>
<li>Variable used from here on, Tensor left dangling</li>
</ol>
<p>What’s the best practice in this case for optimal memory usage? Especially when this may be done for multiple BxCxHxW tensors. To me it begs for a  ‘del &lt;tensor_name&gt;’ after the variable is initialized, but I’m not sure if there is some tricks under the hood to make this unnecessary as I don’t see it done.</p>
<p>It’s often possible to wrap the tensor init within the variable creation but that’s not always conducive to clean code.</p>
<p>Example:</p>
<pre><code>if args.init_rand:
    modifier = torch.normal(input_var.size(), std=0.001).float()
else:
    modifier = torch.zeros(input_var.size()).float()
if args.cuda:
    modifier = modifier.cuda()
modifier_var = autograd.Variable(modifier, requires_grad=True)
del modifier # best to do this by default if modifier never used again in train/eval loop???
</code></pre>
<p>Ross</p>

fmassa: <p><code>Variable</code> share the same memory as its underlying <code>Tensor</code>, so there is no memory savings by deleting it afterwards.<br>
That being said, you can also replace the <code>Tensor</code> variable with a <code>Variable</code> containing the <code>Tensor</code>. E.g.,</p>
<pre><code class="lang-python">x = torch.rand(5)
x = Variable(x)
</code></pre>
<p>The only case where you might see some (small) savings is when you reach the end of the training loop, you might want to delete all references to the input tensor.</p>
<pre><code class="lang-python">for i, (x, y) in enumerate(train_loader):
    x = Variable(x)
    y = Variable(y)
    # compute model and update
    del x, y, output 
</code></pre>
<p>This ensures that you won’t have double the memory necessary for <code>x</code> and <code>y</code>, because <code>train_loader</code> first allocates the memory, and then assign it to <code>x</code>.<br>
But note that if your input tensor is relatively small, this saving by doing that is negligible and not worth it (you also need to make sure that all references to <code>x</code> are deleted, that’s why I <code>del output</code> as well).</p>

rwightman: <p>Thanks, I thought I’d read somewhere about the memory being shared but last time I did a quick test to try that, it looked to be different. Looking back I just realized that I didn’t use an in-place op in my quick test, fixed and confirmed they are in fact sharing memory and all is well with the universe <img src="//discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=5" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>
<p>I’ll keep the second case in mind, with models working on large images where targets are also masks/images, a few hundred MB could tip the balance, but still small in comparison to the model parameters and gradient state.</p>

Deeply: <aside class="quote no-group" data-username="fmassa" data-post="2" data-topic="6000">
<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/fmassa/48/58_2.png" class="avatar"> fmassa:</div>
<blockquote>
<p>for i, (x, y) in enumerate(train_loader): x = Variable(x) y = Variable(y)</p>
</blockquote>
</aside>
<p>How about the case when the tensor is inside a function, if we exit the function, does that mean the data stored to the device (GPU in this case) will be deleted?</p>
<pre><code class="lang-auto">def foo():
    data, target = data.to(device), target.to(device) 
    for i, (data, target) in enumerate(train_loader):
           # do something
           result = ...
    del data, target # is this step necessary?
    return result
 
foo() # first call
foo() # second call
</code></pre>

pinocchio: <p>I am still confused. Many times ppl create intermediate tensors that are created using operations. But these have different values than the tensors they came from. But sometimes we create them just to make the code easier to read but aren’t actually useful. <strong>How does pytorch mange these temp tensors?</strong></p>
<p><strong>In fact, when de we ever have to call <code>del</code>?</strong></p>