How can we release GPU memory cache?

lyakaap: <p>I would like to do a hyper-parameter search so I trained and evaluated with all of the combinations of parameters.<br>
But watching nvidia-smi memory-usage, I found that GPU-memory usage value slightly increased each after a hyper-parameter trial and after several times of trials, finally I got <code>out of memory error</code>. I think it is due to cuda memory caching in no longer use Tensor. I know <code>torch.cuda.empty_cache</code> but it needs do del valuable beforehand. In my case, I couldn’t locate memory consuming variable.<br>
What is the best way to release the GPU memory cache?</p>

albanD: <p>Hi,</p>
<p><code>torch.cuda.empty_cache()</code> (EDITED: fixed function name) will release all the GPU memory cache that can be freed.<br>
If after calling it, you still have some memory that is used, that means that you have a python variable (either torch Tensor or torch Variable) that reference it, and so it cannot be safely released as you can still access it.</p>
<p>You should make sure that you are not holding onto some objects in your code that just grow bigger and bigger with each loop in your search.</p>

lyakaap: <p>Thanks, <a class="mention" href="/u/alband">@albanD</a> !<br>
So, the variables no longer referenced will be freed by using <code>torch.cuda.empty_cache()</code> right?</p>
<p>And I started to locate the memory consuming objects, but I couldn’t locate what variables gave me a bad effect.<br>
As for variables related to cuda, I use same variable name (e.g. model, criterion) in different trials.</p>
<p>Anyway, I suspected below evaluation loop (sorry, it’s version 0.4, maybe version causes the problem?),</p>
<pre><code class="lang-auto">for i, (X, y) in tqdm(enumerate(val_loader), total=len(val_loader)):
    X = Variable(X.cuda())
    y = Variable(y.squeeze().cuda(non_blocking=False))

    with torch.no_grad():
        outputs = model(X)
        loss = criterion(outputs, y)

    prec1, prec5 = accuracy(outputs.data, target, top_k=(1, 5))
    losses.update(loss.data[0], X.size(0))
    top1.update(prec1[0], X.size(0))
    top5.update(prec5[0], X.size(0))
</code></pre>

albanD: <p>So any variable that is no longer reference is freed in the sense that its memory can be used to create new tensors, but this memory is not released to the os (so will still look like it’s used using nvidia-smi).<br>
<code>empty_cache</code> forces the allocator that pytorch uses to release to the os any memory that it kept to allocate new tensors, so it will make a visible change while looking at nvidia-smi, but in reality, this memory was already available to allocate new tensors.</p>
<p>Your code look good, I would double check that things that you send to your logger are not <code>Variables</code> but just python numbers using <code>.item()</code> as necessary.</p>
<p>Also, if you’re using 0.4 (I assume current master), then you should remove <code>Variable</code> and <code>.data</code> from your code and replace <code>loss.data[0]</code> by <code>loss.item()</code> <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=5" title=":wink:" class="emoji" alt=":wink:"></p>

lyakaap: <p>Thank you for detailed answering! I tried other things such as <code>del model, loss, ...</code> but no one helps…<br>
Actually, I am using a little bit older version from the current master branch. But I have thought I should remove Variable and refactor code someday, so your instruction is so helpful, Thanks!</p>

chuong_nguyen: <aside class="quote no-group quote-modified" data-username="albanD" data-post="2" data-topic="14530">
<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/alband/48/215_2.png" class="avatar"> albanD:</div>
<blockquote>
<p>torch.cuda.empty()</p>
</blockquote>
</aside>
<p>AttributeError: module ‘torch.cuda’ has no attribute ‘empty’</p>

albanD: <p>Yes that was a typo I fixed it thanks.</p>

vip: <p>The variables prec1[0] and prec5[0] still hold reference to tensors. These should be replaced with prec1[0].item() and prec5[0].item() respectively. This is due to the fact that the accuracy method part of the pytorch imagenet training example code returns a tensor and can cause memory leak.</p>
<aside class="quote no-group" data-username="lyakaap" data-post="3" data-topic="14530">
<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/lyakaap/48/3070_2.png" class="avatar"> lyakaap:</div>
<blockquote>
<p>top1.update(prec1[0], X.size(0))<br>
top5.update(prec5[0], X.size(0))</p>
</blockquote>
</aside>
<p><a class="mention" href="/u/alband">@albanD</a> Could you please clarify the difference between detach() and item() when called on a tensor. Are these effectively the same?</p>

Weifeng: <p><code>detach()</code> return a tensor that shares storage (and the same device) with origin tensor, while <code>item()</code> return a converted python object.</p>

yxchng: <p>I also face memory problem and using this command works.</p>
<p>Why torch doesn’t empty cache automatically though? Does emptying cache have much overhead?</p>

Ran: <p>I have a question that is it safety to use torch.cuda.empty_cache() before each iteration during training?</p>

ptrblck: <p>This should be safe, but might negatively affect the performance, since PyTorch might need to reallocate this memory again.<br>
What is your use case that you would like to call it for each iteration?</p>

Ran: <p>What is the negative effect? My code runs more and more slowly and sometimes it may interrupt due to memory error, so I have thought to use it before each iteration. I don’t know does it have an effect on the speed?</p>

ptrblck: <p>If you see increasing memory usage, you might accidentally store some tensors with the an attached computation graph. E.g. if you store the <code>loss</code> for printing or debugging purposes, you should save <code>loss.item()</code> instead.</p>
<p>This issue won’t be solved, if you clear the cache repeatedly. As I said this might just trigger unnecessary allocations which will take some time thus potentially slowing down your code.</p>

Ran: <p>I see.<br>
Thanks very much.</p>

mortonjt: <p>Just to clarify, <code>item()</code> deallocates <code>loss</code>?  Its not clear to me what exactly <code>item</code> is doing.</p>

albanD: <p><code>.item()</code> converts a Tensor containing a single element into a python number.<br>
It does not “deallocate” loss. But it won’t keep it alive.</p>

debvrat: <p>This works only some of the times.</p>
<p>Even when I clear out all the variables, restart the kernel, and execute <code>torch.cuda.empty_cache()</code> as the first line in my code, I still get a ‘CUDA out of memory’ error.</p>

dimimal: <p>I have the same issue as well. Has anyone found why does this happen?</p>

albanD: <p>Hi,</p>
<p>Running empty_cache at the beginning of your process is not useful as nothing is allocated yet.<br>
When you restart the kernel, you force all memory to be deallocated.<br>
So if you still run out of memory it is simply because your program requires more than what you have. You will most likely have to reduce the batch size or the size of your model.</p>