Keep getting CUDA OOM error with Pytorch failing to allocate all free memory

pete1213: <p>I encounter random OOM errors during the model traning. It’s like:<br>
<code>RuntimeError: CUDA out of memory. Tried to allocate **8.60 GiB** (GPU 0; 23.70 GiB total capacity; 3.77 GiB already allocated; **8.60 GiB** free; 12.92 GiB reserved in total by PyTorch) If reserved memory is &gt;&gt; allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF</code></p>
<p>As you can see, Pytorch tried to allocate 8.60GiB, the exact amount of memory that’s free now according to the exception report, and failed.</p>
<p>This OOM error keeps poping up randomly during my training, i.e., I can’t locate the exact operation that causes it. Sometimes the last call in the trace is conv1d, sometimes it’s some backward(). And the amount of memory “tried to allocate” also changes all the time, but <strong>always</strong> remains the same as “free memory”.</p>
<p>I’ve been working on training a one-shot NAS model using the single-path method, i.e. at each iteration the model used to forward &amp; backward is not the same. This further add some randomness to this strange error I think…</p>
<p>I’ve done some research on my own. Like setting PYTORCH_CUDA_ALLOC_CONF according to the pytorch doc and also setting PYTORCH_NO_CUDA_MEMORY_CACHING. This two env variable both seemingly solve the problem and help me locate the problem to the pytorch memory allocator with caching mechanism. Perhaps because the allocator is trying to cache all the free memory but fails, I think?</p>
<p>But these env variables can both greatly reduce the training speed. So I wonder if there’s someone who has encountered a similar case before and figured out how to solve it without harming the training efficiency. Thank you very much!</p>

ptrblck: <aside class="quote no-group" data-username="pete1213" data-post="1" data-topic="133896">
<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/p/a8b319/48.png" class="avatar"> pete1213:</div>
<blockquote>
<p>As you can see, Pytorch tried to allocate 8.60GiB, the exact amount of memory that’s free now according to the exception report, and failed.</p>
</blockquote>
</aside>
<p>Since the report shows the memory in GB it could still fail, if either your requested allocation is still larger or if your memory is fragmented and no large enough page can be created.</p>

pete1213: <p>Thank you for your kind reply! Yes, I think fragmentation is more plausible to me as turning off fragmentation helps mitigate this OOM problem (by setting PYTORCH_CUDA_ALLOC_CONF).</p>
<p>I’m more curious about the fact that most OOM error I have here is raised by trying to allocate all the free memory and fails. The amount of memory “trying to allocate” varis every time, but is <strong>always the same</strong>(at least in GB) with free memory.<br>
For most CUDA OOM errors I can find online, “trying to allocate” is bigger than “free”, and they can be tracked down to a specific operation, like creating a large tensor.<br>
That’s the special&amp;interesting point in my case. I want to figure out whether my strange OOM error is caused by some tensor creation or by a buggy allocator inside pytorch.<br>
FYI my pytorch version is 1.10.0, coming from the official nvidia docker image.</p>

ptrblck: <p>The stacktrace should point to an operation which was failing so you could try to inspect it and check its memory requirement by printing the input shapes etc.</p>

sbelharbi: <p>hi,<br>
i am having cuda oom for some time now. but i couldnt find the reason.<br>
memory fragmentation could be the reason…</p>
<p>it was until i upgraded to pytorch 1.9.0 (and now 1.10.0), start using ddp (with single gpu), train with minibatch &gt; 1, and evaluate (for validation) with minibatch of 1, and the trainset of the datasets have a last minibatch of size (3, 4, 8) less than the size of the minibatch (32) (which i just realized it).</p>
<p>more likely cause of oom:</p>
<ul>
<li>
<p>oom used to happen more frequently during validation (even at the first run before start training.). could validation with minibatch size 1 cause a huge memory fragmentation? now, i use torch.cuda.empty_cache() before start running evaluation and right after the end of all evaluation. i run few jobs using this strategy, i dont see oom in validation part. switched from nccl bacnked to gloo. some recommend against nccl for single gpu. it is not really necessary since there is no communication nor synch.</p>
</li>
<li>
<p>now, oom is happening during training. i dont want to use frequently torch.cuda.empty_cache() because i learned that it is expensive. is it possible that the last minibatch in trainset could cause a memory fragmentation? the error occurs after running many epochs. so, memory fragmentation is plausible cause as it does not occur right away.</p>
</li>
</ul>
<pre><code class="lang-bash">    scaler.scale(loss).backward()
  File "home/lib/python3.7/site-packages/torch/_tensor.py", line 307, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
  File "home/lib/python3.7/site-packages/torch/autograd/__init__.py", line 156, in backward
    allow_unreachable=True, accumulate_grad=True)  # allow_unreachable flag
RuntimeError: CUDA out of memory. Tried to allocate 160.00 MiB (GPU 0; 14.76 GiB total capacity; 12.64 GiB already allocated; 161.75 MiB free; 13.26 GiB reserved in total by PyTorch) If reserved memory is &gt;&gt; allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF
</code></pre>
<p>the application here is for cnn.<br>
i read somewhere that in nlp apps, they pad the minbatch to a large max sequence size (because sequences have different length) to:</p>
<ol>
<li>allocate the same blocksize for every minibatch.</li>
<li>when using <code> torch.backends.cudnn.benchmark=True</code>, as i do, it is better to keep the minbatch size the same because cuda has tuned the operations to that size to avoid re-selection of algo every time.</li>
</ol>
<p>so, probably the last minibatch is the one causing the memory fragmentation leading to oom.</p>
<p>less likely cause of oom:</p>
<ul>
<li>pytorch allocator  &gt;= 1.9.0 has an issue? ddp makes it worse?</li>
</ul>
<p>is this the right way to limit block splitting?</p>
<pre><code class="lang-bash">export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128
</code></pre>
<p>what is ‘‘best’’ max_split_size_mb value?<br>
pytorch <a href="https://pytorch.org/docs/stable/notes/cuda.html" rel="noopener nofollow ugc">doc</a> does not really explain much about this choice. they mentioned that this could have huge cost in term of performance (i assume speed) as no cost.<br>
can you explain a bit about the cost?</p>
<p>i learned <a href="https://discuss.pytorch.org/t/gpu-ram-fragmentation-diagnostics/34073">here</a> that defragmenting cuda memory is not a thing, yet.</p>
<p>i have first to fix the last minbatch before trying <code>export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb</code> to  avoid potential cost.</p>
<p>thanks</p>

sbelharbi: <p>filling the last minibatch to match the minibatchsize is not helping. still oom.</p>

sbelharbi: <p>it looks like a gpu issue.<br>
i run the same code over 4 different clusters that have different types of gpus.</p>
<ol>
<li>cluster 1: p100.  3gb &lt; gpu mem used &lt; 6gb. memory usage completely stable. no issue.</li>
<li>cluster 2: v100.  3gb &lt; gpu mem used &lt; 6gb. memory usage completely stable. no issue.</li>
<li>cluster 3: p100.  3gb &lt; gpu mem used &lt; 6gb. memory usage completely stable. no issue.</li>
<li>cluster 4: t4.  6gb &lt; gpu mem used &lt; 16gb. memory usage completely insanely unstable. reached oom.</li>
</ol>
<p>for 4th case, the memory usage starts at 6gb. than, after ~200 epochs of being stable, memory usage starts to oscillate between 6 to 8gb.<br>
later, between 7 and 15gb… crossing 11, 12, 13, 14… gb<br>
i use <code>torch.cuda.empty_cache</code> before and after validation.<br>
i checked, there is no memory leak.<br>
if there is one, it would appear in other cases as well. [there was one couple weeks ago, but i fixed it.]</p>
<p>any idea why t4  are behaving like this?<br>
in all cases, i am using mixed precision training.<br>
because they have plenty of tensor cores, i expect the memory usage to be the lowest.<br>
i am also using ddp, but with single gpu with gloo backend.<br>
the oom happens in the training phase.</p>
<p>pytorch 1.10.0 installation:<br>
<code>pip install torch==1.10.0 -f https://download.pytorch.org/whl/cu111/torch-1.10.0%2Bcu111-cp37-cp37m-linux_x86_64.whl</code></p>
<p>thanks</p>

logy: <aside class="quote no-group" data-username="sbelharbi" data-post="6" data-topic="133896">
<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/f475e1/48.png" class="avatar"> sbelharbi:</div>
<blockquote>
<p><code>export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128</code></p>
</blockquote>
</aside>
<p>excuse me did you solve it ?</p>

sbelharbi: <p>no.<br>
i am benchmarking some methods. and this error happens only with a single method. but not sure what caused it. i am not sure it is method dependent. it could be pytorch version 1.10.0 or something else.</p>
<p>i did several changes in the code, things seem ok now (on other servers). but i didnt try the method that caused oom yet. also, other servers showed the same issue back than. so it is not a t4 issue.</p>
<p>if you are using ddp, the first thing you could try is to change the <a href="https://discuss.pytorch.org/t/dist-barrier-got-out-of-memory/96557/13">backend</a> to mpi (check with your server to see the most stable backend). in version 1.10.0 the backend was causing many issues. now, with mpi, things are fine. but this is server dependent.</p>
<p>for validation, i was accidentally using the ddp_wrapped model. now, i use the true model.</p>
<p>search for memory leaks.<br>
you may be tracking something that is not detached from the graph.</p>
<p>i’ll try the current version of the code on the t4 and report back.</p>
<p>i think torch 1.10.0 has an <a href="https://github.com/pytorch/pytorch/issues/67680" rel="noopener nofollow ugc">issue</a> that causes oom.<br>
if you still cant fix it, i recommend downgrading to torch.1.9.0.</p>
<p>thanks</p>

SM2023: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a> ,</p>
<p>sorry, I face this issue when I want to do fine tunning the GPT-2, My batch size is 16. I have two questions, where is good place to use  “torch.cuda.empty_cache()”  during the fine tunning. and my batch size is 16 , is these setting good to avoid memory issue in my case?</p>
<pre><code class="lang-auto">torch.backends.cudnn.benchmark=True
import os
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:16 "
</code></pre>

SM2023: <p><a class="mention" href="/u/ptrblck">@ptrblck</a>  is it the actual error.</p>
<p>CUDA out of memory. Tried to allocate 192.00 MiB (GPU 0; 14.61 GiB total capacity; 2.07 GiB already allocated; 29.19 MiB free; 2.26 GiB reserved in total by PyTorch) If reserved memory is &gt;&gt; allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF</p>

ptrblck: <aside class="quote no-group" data-username="SM2023" data-post="12" data-topic="133896">
<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/sm2023/48/59719_2.png" class="avatar"> SM2023:</div>
<blockquote>
<p>where is good place to use “torch.cuda.empty_cache()” during the fine tunning.</p>
</blockquote>
</aside>
<p>You shouldn’t free the cache as it won’t avoid OOM errors and will only slow down your code.<br>
PyTorch’s caching allocator will already clear the cache internally if the first allocation fails and will then try to re-allocate the memory. If this second call also fails the OOM error will be re-raised to the user.</p>

SM2023: <p><a class="mention" href="/u/ptrblck">@ptrblck</a>  what should I do to solve the issue of the memory?</p>

SM2023: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> , I appreciate any suggestion.</p>

ptrblck: <p>Check which other process is using the GPU memory as PyTorch isn’t able to use the total 14GB.</p>

Zihan_Wang: <p>I am finetuning the GPT-2/GTP-Neo and meet the same problem.</p>