GPU Memory Leak with Zombie Memory Occupation after Job is Killed

username: pbb
cooked: <p>I have been developing the following library: <a href="https://github.com/TRAIS-Lab/GraSS/blob/main/_GradComp/attributor/attributor.py" class="inline-onebox" rel="noopener nofollow ugc">GraSS/_GradComp/attributor/attributor.py at main · TRAIS-Lab/GraSS · GitHub</a> for a while, and I have ran into a weird GPU memory leak problem on large-scale experiments (specifically, 8B model with 1B token dataset). Let me briefly summarize what this library is trying to do to give some context:</p>
<ol>
<li><code>cache_gradient</code> (in <code>base.py</code>): compute per-sample gradients for train dataloader. No memory leakage for this step.</li>
<li><code>compute_preconditioner</code>: load all per-sample gradients, compute their (layer-wise) outer product and sum them over. At the end, compute their inverses, i.e., preconditioners. See some memory build-up but not significant enough to cause OOM.</li>
<li><code>compute_ifvp</code>: compute the matrix-vector products between the preconditioners (step 2) with the per-sample gradients (step 1). See some memory build-up but not significant enough to cause OOM.</li>
<li><code>attribute</code>: compute per-sample gradients for test dataloader first, and compute all pair-wise inner products between these test per-sample gradients and preconditioned train per-sample gradient (step 3). This step <strong>will</strong> cause OOM.</li>
</ol>
<p>If you look into the code, you’ll find that with <code>offload=disk</code> (i.e., I’ll save/load every gradient/ifvp/preconditioners to/from disk), ideally the code should only occupied a fixed amount of memory since nothing is kept in the memory: I move all the results to cpu followed by a save request, or in the case of loading from disk, it is just prefetching with the dataloader. All actual computations on GPU are fixed size (only a small batches of the entire dataset is loaded) and are simple operations (matrix multiplications).</p>
<p>However, what happened in practice is that the memory built up slowly, and eventually cause OOM in some cases. Another weird thing is that when the task ends (either by keyboard interruption or OOM), there is still some memory occupied on GPU. For instance, this is what happened when I run <code>attribute</code> for a while and then kill the job manually:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/8/3/8347f7d306d4ade91d29261ac26cb5d783a7764b.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/8347f7d306d4ade91d29261ac26cb5d783a7764b" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/8/3/8347f7d306d4ade91d29261ac26cb5d783a7764b_2_610x499.jpeg" alt="image" data-base62-sha1="iJmJQCcsG0zDIyH5sva17LSkeF5" width="610" height="499" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/8/3/8347f7d306d4ade91d29261ac26cb5d783a7764b_2_610x499.jpeg, https://discuss.pytorch.org/uploads/default/optimized/3X/8/3/8347f7d306d4ade91d29261ac26cb5d783a7764b_2_915x748.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/8/3/8347f7d306d4ade91d29261ac26cb5d783a7764b_2_1220x998.jpeg 2x" data-dominant-color="43454B"><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">1436×1176 183 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>The memory builds up slowly (the left part), and when I kill it, there’s still some memory occupying the GPU memory (the right part). This is what leads me to think there’s some memory leakage. I can’t find related posts regarding this behavior, and I wonder how this can be possible.</p>
<p>I’m sorry that I do not provide a MWE since this only happens in large-scale. I would be happy to provide any further information since I’m stuck for quite a while and can’t pinpoint the root cause of this weird phenomenon.</p>
<p>On the other hand, I have tried to profile the memory usage following <a href="https://pytorch.org/blog/understanding-gpu-memory-1/" rel="noopener nofollow ugc">https://pytorch.org/blog/understanding-gpu-memory-1/</a> to debug myself. But I do not see any useful information.</p>
<p>I really have no idea what’s going on, needless to say how to debug it. I really want to understand why this happens and how can I fix this.</p>
<blockquote>
<p>For reference, the following is the code snippet I used to profile the code blocks I mentioned, with the <code>start_record_memory_history()</code>, <code>export_memory_snapshot()</code>, and <code>export_memory_snapshot()</code> defined as in the profile tutorial:</p>
<pre data-code-wrap="python"><code class="lang-python"># Start recording memory snapshot history
        start_record_memory_history()

        # Create dataloader for IFVP with optimal batch size
        train_ifvp_dataloader = self.strategy.create_gradient_dataloader(
            data_type="ifvp",
            batch_size=2,
            pin_memory=True
        )
        torch.cuda.empty_cache()

        # Create the memory snapshot file
        export_memory_snapshot()
        start_record_memory_history()

        logger.info("Starting efficient double-batched attribution computation")

        # Configure test batching for memory efficiency
        test_batch_size = min(32, test_sample_count)  # Process test samples in chunks
        logger.debug(f"Using test batch size: {test_batch_size}")

        iteration = 0
        # Single pass through training IFVP data with nested test batching
        for chunk_tensor, batch_mapping in tqdm(train_ifvp_dataloader, desc="Computing attribution"):
            # Move train chunk to device
            chunk_tensor_device = self.strategy.move_to_device(chunk_tensor).to(dtype=all_test_gradients.dtype)

            # Process test gradients in batches to save memory
            for test_start in range(0, test_sample_count, test_batch_size):
                test_end = min(test_start + test_batch_size, test_sample_count)
                test_batch = all_test_gradients[test_start:test_end]

                # Move test batch to device
                test_batch_device = self.strategy.move_to_device(test_batch)

                # Efficient batched matrix multiplication for this (train_chunk, test_batch) pair
                # Shape: (chunk_samples, proj_dim) @ (proj_dim, test_batch_samples) -&gt; (chunk_samples, test_batch_samples)
                chunk_scores = torch.matmul(chunk_tensor_device, test_batch_device.t())

                # Map chunk results back to global sample indices
                for batch_idx, (start_row, end_row) in batch_mapping.items():
                    if batch_idx not in batch_to_sample_mapping:
                        continue

                    train_start, train_end = batch_to_sample_mapping[batch_idx]
                    batch_scores = chunk_scores[start_row:end_row]
                    IF_score[train_start:train_end, test_start:test_end] = batch_scores.to(IF_score.device)

                # Clean up test batch from device
                # del test_batch_device, chunk_scores
                torch.cuda.empty_cache()

            # Clean up train chunk from device
            # del chunk_tensor_device
            torch.cuda.empty_cache()
            iteration += 1
            if iteration == 100:
                break

        # Create the memory snapshot file
        export_memory_snapshot()
</code></pre>
</blockquote>

username: ptrblck
cooked: <aside class="quote no-group" data-username="pbb" data-post="1" data-topic="220338">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/pbb/48/77165_2.png" class="avatar"> pbb:</div>
<blockquote>
<p>and when I kill it, there’s still some memory occupying the GPU memory (the right part</p>
</blockquote>
</aside>
<p>Did you check if the process was really killed? Even if PyTorch would leak memory once the process is killed the memory would be released by destroying the CUDA context.</p>

username: pbb
cooked: <p>Hi, I rechecked that in both <code>nvtop</code> and <code>htop</code>, and the following is what I have:</p>
<ol>
<li><code>nvtop</code>: I kill the job with <code>ctrl+d</code> when I see a memory built up, and <code>nvtop</code> shows that the memory occupation after the job is terminated.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/9/49118ca66f65d975f6bac419228802f51940d16f.png" data-download-href="https://discuss.pytorch.org/uploads/default/49118ca66f65d975f6bac419228802f51940d16f" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/4/9/49118ca66f65d975f6bac419228802f51940d16f_2_329x500.png" alt="image" data-base62-sha1="aqoscde5WoC3FPsBQP6EefikpNd" width="329" height="500" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/4/9/49118ca66f65d975f6bac419228802f51940d16f_2_329x500.png, https://discuss.pytorch.org/uploads/default/optimized/3X/4/9/49118ca66f65d975f6bac419228802f51940d16f_2_493x750.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/4/9/49118ca66f65d975f6bac419228802f51940d16f_2_658x1000.png 2x" data-dominant-color="414347"><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">2012×3054 1.25 MB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></li>
<li><code>htop</code>: Meanwhile, I also checked the <code>htop</code> and didn’t see anything suspicious or job-like process under my user (<code>pbb</code>).:</li>
</ol>
<pre data-code-wrap="bash"><code class="lang-bash">2965915 pbb         20   0 22912 13632  8640 S   0.0  0.0  0:00.04 /usr/lib/systemd/systemd --user
2965916 pbb         20   0  185M 11712     0 S   0.0  0.0  0:00.00 (sd-pam)
2965924 pbb         20   0  9344  4736  3520 S   0.0  0.0  0:00.00 /bin/bash /var/spool/slurmd/job242578/slurm_script
2965930 pbb         20   0  7552  1408   640 S   0.0  0.0  0:00.00 sleep 9000
2966010 pbb         20   0 31936 10624  2368 S   0.0  0.0  0:00.01 sshd: pbb@pts/0
2966011 pbb         20   0 11072  5632  4032 S   0.0  0.0  0:00.01 -bash
2966095 pbb         20   0 31936 10624  2368 S   0.0  0.0  0:00.00 sshd: pbb@pts/1
2966096 pbb         20   0 11072  5056  3648 S   0.0  0.0  0:00.01 -bash
2966338 pbb         20   0 31936 10624  2368 S   0.0  0.0  0:00.02 sshd: pbb@pts/2
2966339 pbb         20   0 11072  5120  3648 S   0.0  0.0  0:00.01 -bash
2966423 pbb         20   0 31680  7296  3840 R   0.0  0.0  0:05.20 htop
2966759 pbb         20   0 35072 18560  3904 S   0.7  0.0  0:01.38 nvtop
</code></pre>
<p>If this helps with the debugging, I’m using the TACC VISTA cluster (<a href="https://docs.tacc.utexas.edu/hpc/vista/" class="inline-onebox" rel="noopener nofollow ugc">Vista - TACC HPC Documentation</a>)'s Grace Hopper subsystem (arch64).</p>

username: ptrblck
cooked: <aside class="quote no-group" data-username="pbb" data-post="4" data-topic="220338">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/pbb/48/77165_2.png" class="avatar"> pbb:</div>
<blockquote>
<p>and <code>nvtop</code> shows that the memory occupation after the job is terminated.</p>
</blockquote>
</aside>
<aside class="quote no-group" data-username="pbb" data-post="1" data-topic="220338">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/pbb/48/77165_2.png" class="avatar"> pbb:</div>
<blockquote>
<p>and when I kill it, there’s still some memory occupying the GPU memory (the right part).</p>
</blockquote>
</aside>
<p>Does this mean you cannot reproduce any memory usage after you terminated the process?</p>

username: pbb
cooked: <aside class="quote no-group" data-username="ptrblck" data-post="5" data-topic="220338">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>Does this mean you cannot reproduce any memory usage after you terminated the process?</p>
</blockquote>
</aside>
<p>What do you mean by “reproducing memory usage after terminating the process”? I think in the following:</p>
<aside class="quote no-group" data-username="pbb" data-post="4" data-topic="220338">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/pbb/48/77165_2.png" class="avatar"> pbb:</div>
<blockquote>
<p>and <code>nvtop</code> shows that the memory occupation after the job is terminated.</p>
</blockquote>
</aside>
<p>what I try to show is that there’s still (according to <code>nvtop</code>) some memory occupying the GPU memory after I manually killed the job (verified in both <code>nvtop</code> and <code>htop</code>: seems like every job is killed). (Might not be significant since I killed the job after the first memory built up: but if you look closely, the yellow line is non-zero and there’s nothing running)</p>
<p>Same for the following:</p>
<aside class="quote no-group" data-username="pbb" data-post="1" data-topic="220338">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/pbb/48/77165_2.png" class="avatar"> pbb:</div>
<blockquote>
<p>and when I kill it, there’s still some memory occupying the GPU memory (the right part).</p>
</blockquote>
</aside>