VRAM leak during inference despite torch.no_grad()

marco.moldovan: <p>I am trying to encode documents sentence-wise with a huggingface transformer module. I’m using the very small <code>google/bert_uncased_L-2_H-128_A-2</code> pretrained model with the following code:</p>
<pre><code class="lang-auto">def pre_encode_wikipedia(model, tokenizer, device, save_path):
  
  document_data_list = []

  for iteration, document in enumerate(wikipedia_small['text']):
    torch.cuda.empty_cache()

    sentence_embeds_per_doc = [torch.randn(128)]
    attention_mask_per_doc = [1]
    special_tokens_per_doc = [1]

    doc_split = nltk.sent_tokenize(document)
    doc_tokenized = tokenizer.batch_encode_plus(doc_split[:512], padding='longest', truncation=True, max_length=512, return_tensors='pt')

    for key, value in doc_tokenized.items():
      doc_tokenized[key] = doc_tokenized[key].to(device)

    with torch.no_grad():  
      doc_encoded = model(**doc_tokenized)

    for sentence in doc_encoded['last_hidden_state']:
      cpu_sentence = sentence[0].to('cpu')
      sentence_embeds_per_doc.append(cpu_sentence)
      attention_mask_per_doc.append(1)
      special_tokens_per_doc.append(0)

    sentence_embeds = torch.stack(sentence_embeds_per_doc)
    attention_mask = torch.FloatTensor(attention_mask_per_doc)
    special_tokens_mask = torch.FloatTensor(special_tokens_per_doc)

    document_data = torch.utils.data.TensorDataset(*[sentence_embeds, attention_mask, special_tokens_mask])
    torch.save(document_data, f'{save_path}{time.strftime("%Y%m%d-%H%M%S")}{iteration}.pt')
    print(f"Document at {iteration} encoded and saved.")
</code></pre>
<p>After about a few hundred to a couple thousand iterations on my local GTX 1060 3GB I get an error saying that my <strong>CUDA is out of memory</strong>. Running this code on Colab with more GPU RAM more iterations usually. Here’s the error:<br>
<code>RuntimeError: CUDA out of memory. Tried to allocate 112.00 MiB (GPU 0; 3.00 GiB total capacity; 1.95 GiB already allocated; 0 bytes free; 1.98 GiB reserved in total by PyTorch)</code><br>
Note that the exact MiBs it unsuccessfully tries to allocate changes from try to try.</p>
<p><strong>Things I’ve tried:</strong></p>
<ul>
<li>Adding <code>torch.cuda.empty_cache()</code> to the start of every iteration to clear out previously held tensors</li>
<li>Wrapping the model in <code> with torch.no_grad():</code> to disable the computation graph</li>
<li>Setting <code>model.eval()</code> to disable any stochastic properties that might take up memory</li>
<li>Sending the output straight to CPU in hopes to free up memory</li>
<li>Plotting the length of the input documents to check if there were any outliers and clipping them to 512 sentences</li>
</ul>
<p>I’m baffled as to why my memory keeps overflowing. I’ve trained several models of bigger sizes, applying all the standard practices of a training loop (<code>optimizer.zero_grad()</code>, etc.) I’ve never had this problem. Why does it appear during this seemingly trivial task?</p>
<p>I’m attaching a screenshot of my VRAM usage during an overflow, it appears to me that tensors don’t accumulate but one specific input triggers the crash which is strange because I’m clipping the long inputs.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/6/d/6d68672e643fea763f8ee9f7e3e6c98474e0f3c5.png" data-download-href="https://discuss.pytorch.org/uploads/default/6d68672e643fea763f8ee9f7e3e6c98474e0f3c5" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/6/d/6d68672e643fea763f8ee9f7e3e6c98474e0f3c5_2_690x217.png" alt="image" data-base62-sha1="fBRJ3Lk18oyawwY2pJKVB8DQvE9" width="690" height="217" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/6/d/6d68672e643fea763f8ee9f7e3e6c98474e0f3c5_2_690x217.png, https://discuss.pytorch.org/uploads/default/optimized/3X/6/d/6d68672e643fea763f8ee9f7e3e6c98474e0f3c5_2_1035x325.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/6/d/6d68672e643fea763f8ee9f7e3e6c98474e0f3c5_2_1380x434.png 2x" data-dominant-color="F5F8FA"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1854×584 36.4 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>Running the program on CPU works but I still see spikes in RAM usage, but doesn’t crash because memory swapping kicks in (which doesn’t work for VRAM).</p>