How to maximize CPU <==> GPU memory transfer speeds?

username: GuillaumeTong
cooked: <p>Hi, I am looking into different ways to optimize the running speed of my code, and one of these is looking at the speed of memory transfers between CPU and GPU, and the performances that I have measured do not seem to match up to the hardware’s theoretical one. I have written the following script:</p>
<p>(note: I decided to re-use the same pinned memory buffer, in order to avoid the overhead from re-allocating it over and over again)</p>
<pre><code class="lang-python">import argparse
import time

import torch
from tqdm import trange


def stress_vram_transfer(
        batch_size=10,
        warmup=5,
        repeats=100,
        frame_shape=(3, 3840, 2160),
        use_pinned_memory=True,
):
    tensor = torch.randn((batch_size, *frame_shape))
    if use_pinned_memory:
        tensor = tensor.pin_memory()
    in_loop_tensor = tensor

    for device_id in range(torch.cuda.device_count()):
        print(f"Starting test for device {device_id}: {torch.cuda.get_device_properties(device_id)}")
        for _ in trange(warmup, desc="warmup"):
            in_loop_tensor = in_loop_tensor.cuda()
            if use_pinned_memory:
                tensor[:] = in_loop_tensor.cpu()
                in_loop_tensor = tensor
            else:
                in_loop_tensor = in_loop_tensor.cpu()
        start = time.perf_counter()
        for _ in trange(repeats, desc="test"):
            in_loop_tensor = in_loop_tensor.cuda()
            if use_pinned_memory:
                tensor[:] = in_loop_tensor.cpu()
                in_loop_tensor = tensor
            else:
                in_loop_tensor = in_loop_tensor.cpu()
        end = time.perf_counter()
        print(f"Total time taken: {end-start:.2f}")


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--batch_size", type=int, default=10)
    parser.add_argument("--warmup", type=int, default=5)
    parser.add_argument("--repeats", type=int, default=100)
    parser.add_argument("--frame_shape", type=int, nargs=3, default=(3, 3840, 2160))
    parser.add_argument("--use_pinned_memory", type=bool, default=True)
    parser.add_argument('--no_pin', dest='use_pinned_memory', action='store_false')
    args = parser.parse_args()

    args = dict(vars(args))
    print(args)
    stress_vram_transfer(**args)
</code></pre>
<p>Using this, and running on an RTX3090, this is what I get:</p>
<pre><code class="lang-bash">$ CUDA_VISIBLE_DEVICES=1 python memory_transfer_test.py --batch_size 50 --no_pin
{'batch_size': 50, 'warmup': 5, 'repeats': 100, 'frame_shape': (3, 3840, 2160), 'use_pinned_memory': False}
Starting test for device 0: _CudaDeviceProperties(name='NVIDIA GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)
warmup: 100%|_____________________________________________________________________________________________________________________________________________| 5/5 [00:13&lt;00:00,  2.71s/it]
test: 100%|___________________________________________________________________________________________________________________________________________| 100/100 [03:42&lt;00:00,  2.22s/it]
Total time taken: 222.21
</code></pre>
<pre><code class="lang-bash">$ CUDA_VISIBLE_DEVICES=1 python memory_transfer_test.py --batch_size 50
{'batch_size': 50, 'warmup': 5, 'repeats': 100, 'frame_shape': (3, 3840, 2160), 'use_pinned_memory': True}
Starting test for device 0: _CudaDeviceProperties(name='NVIDIA GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)
warmup: 100%|_____________________________________________________________________________________________________________________________________________| 5/5 [00:13&lt;00:00,  2.64s/it]
test: 100%|___________________________________________________________________________________________________________________________________________| 100/100 [04:23&lt;00:00,  2.63s/it]
Total time taken: 263.24
</code></pre>
<p>These results are surprising on several fronts:</p>
<ol>
<li>The memory transfer speed is MUCH slower than what the hardware promises: 6770MB vRAM usage by my process is being reported by nvidia-smi, and each step is taking about 2.22s transferring it both ways, which would equate to 2*6770MB/2.22s = 6100MB/s. An RTX3090 is supposed to have <a href="https://www.techpowerup.com/gpu-specs/geforce-rtx-3090.c3622" rel="noopener nofollow ugc">936.2 GB/s</a> memory bandwidth: even if I divide that by 4 accounting for my card only having access to 4x PCIE lanes VS the maximum of 16x, I am still faced with at least a 10x discrepancy in that memory bandwidth.</li>
<li>The <code>use_pinned_memory</code> version actually performs slower than the no_pin version. Looking at the <a href="https://pytorch.org/docs/stable/notes/cuda.html#use-pinned-memory-buffers" rel="noopener nofollow ugc">PyTorch documentation</a>, pin_memory() is recommended for faster Host to GPU copies…</li>
</ol>
<p>Given these observations, I have the following questions:</p>
<ol>
<li>Am I wrong to expect the memory bandwidth advertised for my GPU to match up with the tensor transfer speeds in PyTorch?</li>
<li>Am I using pin_memory() correctly in this test? From my understanding, a major advantage this function brings is the asynchronous GPU copies, but that does not seem like it can be exploited in this scenario.</li>
<li>If using pin_memory() is supposed to help with “Host to GPU copies”, does it also apply to GPU to Host copies? Or is there a separate trick to use?</li>
<li>If the information from point 3 on <a href="https://towardsdatascience.com/optimize-pytorch-performance-for-speed-and-memory-efficiency-2022-84f453916ea6" rel="noopener nofollow ugc">this page</a> is to be believed, PyTorch will actually copy non-pinned tensors to pinned memory before copying it to GPU. Is there any reason we could expect that to be slower than manually copying the tensor to pinned memory, then asking PyTorch to copy it to GPU?</li>
</ol>

username: aifartist
cooked: <p>I definitely want to pay attention to any responses on this.  I say that because I’ve noticed the trend that as the GPU’s and the software and the algorithms used in the software get faster and faster then simple things like saving a inference generated image in Stable Diffusion becomes a significant part of the overall time.  And it is no different here.  If a result is computed very quickly then the transfer to and from the GPU becomes significant.  I have a 4090 and a fast i9-13900K cpu so I want to see if this memory pinning helps.</p>
<p>Prior to starting in this new field of AI and GPU’s I was a perf expert in conventional systems.  There was a similar memory pinning thing done for things like RDMA.  The trick was having enough data to transfer such that the overhead of pinning/unpinning memory didn’t wipe out the gain.  I just beginning to learn this stuff so I don’t know if NVIDIA has any overhead with pinning.  Certainly pinning memory pages on the CPU’s memory does add some overhead.  The trick I learned was to reserve a pinned memory region once and then keep reusing it instead of doing the pin for individual transfer operations.  I wonder if a similar concept exists here.  Hmmm, silly me…  I just noticed you actually are doing that.</p>
<p>I’ll experiment with this myself.  The torch doc’s I just looked at don’t say whether the memory pinning applies to CPU or GPU memory.  Since I’m on Linux I can simply pin the entire memory space of the app process to guarantee it is pinned.  Yes, I know that is dangerous if a process is too big.  But it is an experiment to see if there is any perf impact and I know what I’m doing.  Another technique would be to strace the process to see if there are many pin/unpin calls for each transfer being done.  But that’ll be for tomorrow.</p>

username: aifartist
cooked: <p>This looks like it’ll be a good read for me to better understand the subject.  Too tired right now…</p><aside class="onebox allowlistedgeneric" data-onebox-src="https://developer.nvidia.com/blog/how-optimize-data-transfers-cuda-cc/">
  <header class="source">
      <img src="https://developer-blogs.nvidia.com/wp-content/themes/nvidia/dist/images/favicon_300a1064.ico" class="site-icon" width="48" height="48">

      <a href="https://developer.nvidia.com/blog/how-optimize-data-transfers-cuda-cc/" target="_blank" rel="noopener nofollow ugc" title="01:20AM - 05 December 2012">NVIDIA Technical Blog – 5 Dec 12</a>
  </header>

  <article class="onebox-body">
    <div class="aspect-image" style="--aspect-ratio:503/500;"><img src="https://developer-blogs.nvidia.com/wp-content/uploads/2012/10/CUDA_Cube_1K.jpg" class="thumbnail" width="503" height="500"></div>

<h3><a href="https://developer.nvidia.com/blog/how-optimize-data-transfers-cuda-cc/" target="_blank" rel="noopener nofollow ugc">How to Optimize Data Transfers in CUDA C/C++ | NVIDIA Technical Blog</a></h3>

  <p>In the previous three posts of this CUDA C &amp; C++ series we laid the groundwork for the major thrust of the series: how to optimize CUDA C/C++ code. In this and the following post we begin our…</p>


  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>


username: ptrblck
cooked: <ol>
<li>
<p>I would recommend reading through the linked blog post about memory transfers and and to run a few benchmarks if you are interested in profiling your system (without PyTorch to reduce the complexity of the entire stack).</p>
</li>
<li>
<p>Using pinned memory would avoid a staging copy and should perform better and also allow you to use non blocking data transfers as also explained in the blog post.</p>
</li>
<li>
<p>Yes, using <code>pin_memory=True</code> will allow you to use non blocking copies allowing you to overlap the data transfer with another operation. However, if the very next operation depends on the transferred tensor there won’t be any overlapping operation so I’m unsure what your expectations in your test would be.</p>
</li>
<li>
<p>Yes, device to host copies can also use pinned memory, but you would need to synchronize the device before accessing the data.</p>
</li>
<li>
<p>No, unless your overall system performance suffers from too much pinned memory by the process and starts to swap memory.</p>
</li>
</ol>
<p>Here is a small example showing a non blocking D2H copy and shows the common mistake causing corrupt data by not properly synchronizing the code:</p>
<pre><code class="lang-python">stream = torch.cuda.current_stream()
dst = "cpu"
non_blocking = True
a = torch.randn(1000000, device="cuda")
ref = a.cpu()

torch.cuda.synchronize()
# Pushes an 2 second spin to stream so if the copy is non blocking,
# stream will almost surely be active when we query().
torch.cuda._sleep(int(2000 * torch.testing._internal.common_utils.get_cycles_per_ms()))
b = a.to(device=dst, non_blocking=non_blocking)
print(stream.query(), not non_blocking)
# False False
print((b - ref).abs().max())
# tensor(7.3916)
stream.synchronize()
print((b - ref).abs().max())
# tensor(0.)
print(b.is_pinned())
# True
</code></pre>

username: GuillaumeTong
cooked: <p>Thank you very much for this thorough reply. This is very enlightening.</p>
<p>1: The benchmark in the blog post <a class="mention" href="/u/aifartist">@aifartist</a> linked to does seem very relevant to test the system’s ability without PyTorch in the mix. I’d like to run it, but I am not familiar with C++, so I will need some time to figure out how to set up the correct environment and compile it. Any pointer will be appreciated.</p>
<p>2 3 4 5: The <code>.to(device="cpu", non_blocking=True)</code> method is indeed useful even in my test, which does not leverage the actual non-blocking nature of the calls (I assume that’s thanks to avoiding a pinned ==&gt; paged ==&gt; pinned round trip). Is this behavior of returning pinned CPU tensors mentioned anywhere in the documentation, however?</p>
<p>6: I assume allocating pinned memory takes a bit of time. Would I be wrong to hope for some increase in speed if I manage to recycle the same pinned memory buffer repeatedly?</p>
<p>7: If yes, is there a way to ensure that in PyTorch currently? <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.to.html" rel="noopener nofollow ugc"><code>Tensor.to()</code></a> seems to be lacking the <code>out=</code> argument found in many other operations such as <a href="https://pytorch.org/docs/stable/generated/torch.add.html#torch.add" rel="noopener nofollow ugc"><code>torch.add()</code></a></p>
<p>For your reference, here is the version of my code after updating it with <code>non_blocking</code>:</p>
<pre><code class="lang-python">import argparse
import time

import torch
from tqdm import trange


def stress_vram_transfer(
        batch_size=10,
        warmup=5,
        repeats=100,
        frame_shape=(3, 3840, 2160),
        use_pinned_memory=True,
):
    tensor = torch.randn((batch_size, *frame_shape))
    if use_pinned_memory:
        tensor = tensor.pin_memory()

    for device_id in range(torch.cuda.device_count()):
        print(f"Starting test for device {device_id}: {torch.cuda.get_device_properties(device_id)}")
        for _ in trange(warmup, desc="warmup"):
            tensor = tensor.to(device=device_id, non_blocking=use_pinned_memory)
            tensor = tensor.to(device="cpu", non_blocking=use_pinned_memory)
            if use_pinned_memory:
                torch.cuda.current_stream(device=device_id).synchronize()
        start = time.perf_counter()
        for _ in trange(repeats, desc="test"):
            tensor = tensor.to(device=device_id, non_blocking=use_pinned_memory)
            tensor = tensor.to(device="cpu", non_blocking=use_pinned_memory)
            if use_pinned_memory:
                torch.cuda.current_stream(device=device_id).synchronize()
        end = time.perf_counter()
        print(f"Total time taken: {end-start:.2f}")


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--batch_size", type=int, default=10)
    parser.add_argument("--warmup", type=int, default=5)
    parser.add_argument("--repeats", type=int, default=100)
    parser.add_argument("--frame_shape", type=int, nargs=3, default=(3, 3840, 2160))
    parser.add_argument("--use_pinned_memory", type=bool, default=True)
    parser.add_argument('--no_pin', dest='use_pinned_memory', action='store_false')
    args = parser.parse_args()

    args = dict(vars(args))
    print(args)
    stress_vram_transfer(**args)

</code></pre>
<p>The time to run the test went from 263.24s down to 157.48s, beating the no_pin version’s 222.21s, and bringing the memory transfer speed to roughly 8600MB/s. That is better, but still far behind the hundreds of GB/s I was hoping for.</p>

username: aifartist
cooked: <p><a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>If I “strace -f” my GPU app I find not a single mlockxxx call nor a mmap with MAP_LOCKED call.</p>
<p>I presume there isn’t a major bug in pytorch where they are missing doing the memory pin such that crashes might occur under stress if the system starts swapping pages.  I only know of the two ways mentioned to pin memory pages.</p>

username: ptrblck
cooked: <p>PyTorch uses <code>cudaHostAlloc</code>, but you can also allocate <code>cudaHostRegister</code> via <code>torch.cuda.cudart()</code> in case you want to manage the host memory with <code>MAP_LOCKED</code> manually.</p>

username: GuillaumeTong
cooked: <aside class="quote no-group" data-username="GuillaumeTong" data-post="5" data-topic="173855">
<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/guillaumetong/48/46976_2.png" class="avatar"> GuillaumeTong:</div>
<blockquote>
<p>6: I assume allocating pinned memory takes a bit of time. Would I be wrong to hope for some increase in speed if I manage to recycle the same pinned memory buffer repeatedly?</p>
<p>7: If yes, is there a way to ensure that in PyTorch currently? <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.to.html" rel="noopener nofollow ugc"><code>Tensor.to()</code></a> seems to be lacking the <code>out=</code> argument found in many other operations such as <a href="https://pytorch.org/docs/stable/generated/torch.add.html#torch.add" rel="noopener nofollow ugc"><code>torch.add()</code></a></p>
</blockquote>
</aside>
<p>Regarding this, I found out that <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.copy_.html#torch-tensor-copy" rel="noopener nofollow ugc">Tensor.copy_</a> enables exactly that: If you pre-allocate the pinned tensor, you can use <code>pinned_tensor.copy_(non_blocking=True)</code> to copy the CUDA tensor directly into it, and vice versa with copying pinned tensors into CUDA tensors.</p>
<p>However, when testing out this optimization, I saw no measurable performance increase. I suspect this might be because <a href="https://pytorch.org/docs/stable/notes/cuda.html#memory-management" rel="noopener nofollow ugc">PyTorch already uses a caching memory allocator</a> that efficiently takes care of this in the background, at least for this simple test case.</p>