• Tutorials >
  • A guide on good usage of non_blocking and pin_memory() in PyTorch
Shortcuts

PyTorch中non_blockingpin_memory()的良好使用指南

创建于:2024年7月31日 | 最后更新:2024年8月1日 | 最后验证:2024年11月5日

作者: Vincent Moens

介绍

在许多PyTorch应用中,将数据从CPU传输到GPU是基础操作。 用户理解在设备之间移动数据的最有效工具和选项至关重要。 本教程探讨了PyTorch中设备到设备数据传输的两种关键方法: pin_memory()to()non_blocking=True 选项。

你将学到什么

优化从CPU到GPU的张量传输可以通过异步传输和内存固定来实现。然而,有一些重要的注意事项:

  • 使用 tensor.pin_memory().to(device, non_blocking=True) 可能比直接的 tensor.to(device) 慢两倍。

  • 通常,tensor.to(device, non_blocking=True) 是提高传输速度的有效选择。

  • cpu_tensor.to("cuda", non_blocking=True).mean()正确执行时,尝试cuda_tensor.to("cpu", non_blocking=True).mean()将会导致错误的输出。

前言

本教程中报告的性能取决于用于构建教程的系统。 尽管结论适用于不同的系统,但具体的观察结果可能会因可用硬件的不同而略有差异,尤其是在较旧的硬件上。 本教程的主要目标是提供一个理论框架,用于理解CPU到GPU的数据传输。 然而,任何设计决策都应根据个别情况进行调整,并以基准吞吐量测量为指导, 以及手头任务的具体要求。

import torch

assert torch.cuda.is_available(), "A cuda device is required to run this tutorial"

本教程需要安装tensordict。如果您的环境中还没有tensordict,请在一个单独的单元格中运行以下命令来安装它:

# Install tensordict with the following command
!pip3 install tensordict

我们首先概述围绕这些概念的理论,然后转向这些功能的具体测试示例。

背景

内存管理基础

当在PyTorch中创建一个CPU张量时,这个张量的内容需要放置在内存中。我们这里所说的内存是一个相当复杂的概念,值得仔细研究。我们区分了由内存管理单元处理的两种类型的内存:RAM(为了简化)和磁盘上的交换空间(可能是硬盘,也可能不是)。磁盘和RAM(物理内存)中的可用空间共同构成了虚拟内存,这是可用总资源的抽象。简而言之,虚拟内存使得可用空间比单独在RAM中找到的空间更大,并产生主内存比实际更大的错觉。

在正常情况下,常规的CPU张量是可分页的,这意味着它被分成称为页的块,这些块可以存在于虚拟内存中的任何位置(无论是在RAM中还是在磁盘上)。如前所述,这有一个优势,即内存看起来比实际的主内存要大。

通常,当程序访问一个不在RAM中的页面时,会发生“页面错误”,然后操作系统(OS)将这个页面带回RAM(“换入”或“页面调入”)。 反过来,操作系统可能需要换出(或“页面调出”)另一个页面,以便为新页面腾出空间。

与可分页内存相比,固定(或页面锁定或不可分页)内存是一种不能被交换到磁盘的内存类型。 它允许更快和更可预测的访问时间,但缺点是它比可分页内存(即主内存)更有限。

CUDA 和(非)可分页内存

要理解CUDA如何将张量从CPU复制到CUDA,让我们考虑上述两种场景:

  • 如果内存是页锁定的,设备可以直接在主内存中访问内存。内存地址是明确定义的,需要读取这些数据的函数可以显著加速。

  • 如果内存是可分页的,所有页面在发送到GPU之前都必须被带到主内存中。 这个操作可能需要时间,并且比在页锁定张量上执行时更不可预测。

更准确地说,当CUDA将可分页数据从CPU发送到GPU时,它必须首先创建该数据的页锁定副本,然后再进行传输。

异步与同步操作使用 non_blocking=True (CUDA cudaMemcpyAsync)

当从主机(例如,CPU)执行复制到设备(例如,GPU)时,CUDA工具包提供了与主机同步或异步执行这些操作的模式。

在实践中,当调用to()时,PyTorch总是会调用cudaMemcpyAsync。 如果non_blocking=False(默认值),则在每次cudaMemcpyAsync之后都会调用cudaStreamSynchronize,使得对to()的调用在主线程中阻塞。 如果non_blocking=True,则不会触发同步,主机上的主线程不会被阻塞。 因此,从主机的角度来看,多个张量可以同时发送到设备,因为线程不需要等待一个传输完成才能启动另一个传输。

注意

通常,传输在设备端是阻塞的(即使在主机端不是): 在设备上的复制不能在另一个操作执行时发生。 然而,在一些高级场景中,复制和内核执行可以在GPU端同时进行。 如下例所示,要实现这一点,必须满足三个要求:

  1. 设备必须至少有一个空闲的DMA(直接内存访问)引擎。现代GPU架构,如Volterra、Tesla或H100设备,拥有多个DMA引擎。

  2. 传输必须在单独的、非默认的cuda流上进行。在PyTorch中,cuda流可以使用Stream来处理。

  3. 源数据必须位于固定内存中。

我们通过运行以下脚本的配置文件来演示这一点。

import contextlib

from torch.cuda import Stream


s = Stream()

torch.manual_seed(42)
t1_cpu_pinned = torch.randn(1024**2 * 5, pin_memory=True)
t2_cpu_paged = torch.randn(1024**2 * 5, pin_memory=False)
t3_cuda = torch.randn(1024**2 * 5, device="cuda:0")

assert torch.cuda.is_available()
device = torch.device("cuda", torch.cuda.current_device())


# The function we want to profile
def inner(pinned: bool, streamed: bool):
    with torch.cuda.stream(s) if streamed else contextlib.nullcontext():
        if pinned:
            t1_cuda = t1_cpu_pinned.to(device, non_blocking=True)
        else:
            t2_cuda = t2_cpu_paged.to(device, non_blocking=True)
        t_star_cuda_h2d_event = s.record_event()
    # This operation can be executed during the CPU to GPU copy if and only if the tensor is pinned and the copy is
    #  done in the other stream
    t3_cuda_mul = t3_cuda * t3_cuda * t3_cuda
    t3_cuda_h2d_event = torch.cuda.current_stream().record_event()
    t_star_cuda_h2d_event.synchronize()
    t3_cuda_h2d_event.synchronize()


# Our profiler: profiles the `inner` function and stores the results in a .json file
def benchmark_with_profiler(
    pinned,
    streamed,
) -> None:
    torch._C._profiler._set_cuda_sync_enabled_val(True)
    wait, warmup, active = 1, 1, 2
    num_steps = wait + warmup + active
    rank = 0
    with torch.profiler.profile(
        activities=[
            torch.profiler.ProfilerActivity.CPU,
            torch.profiler.ProfilerActivity.CUDA,
        ],
        schedule=torch.profiler.schedule(
            wait=wait, warmup=warmup, active=active, repeat=1, skip_first=1
        ),
    ) as prof:
        for step_idx in range(1, num_steps + 1):
            inner(streamed=streamed, pinned=pinned)
            if rank is None or rank == 0:
                prof.step()
    prof.export_chrome_trace(f"trace_streamed{int(streamed)}_pinned{int(pinned)}.json")

在Chrome中加载这些性能跟踪(chrome://tracing)显示以下结果:首先,让我们看看如果在主流的可分页张量发送到GPU后执行t3_cuda上的算术运算会发生什么:

benchmark_with_profiler(streamed=False, pinned=False)

使用固定的张量并不会显著改变跟踪,两个操作仍然会连续执行:

benchmark_with_profiler(streamed=False, pinned=True)

将可分页的张量发送到GPU的单独流上也是一个阻塞操作:

benchmark_with_profiler(streamed=True, pinned=False)

只有固定的张量副本在单独的流上与在主流上执行的另一个cuda内核重叠:

benchmark_with_profiler(streamed=True, pinned=True)

PyTorch 视角

pin_memory()

PyTorch 提供了通过 pin_memory() 方法和构造函数参数创建并发送张量到页锁定内存的可能性。 在初始化了 CUDA 的机器上,CPU 张量可以通过 pin_memory() 方法转换为锁定内存。重要的是,pin_memory 在主线程上是阻塞的:它会等待张量被复制到页锁定内存后再执行下一个操作。 可以使用 zeros()ones() 和其他构造函数直接在锁定内存中创建新的张量。

让我们检查一下固定内存和将张量发送到CUDA的速度:

import torch
import gc
from torch.utils.benchmark import Timer
import matplotlib.pyplot as plt


def timer(cmd):
    median = (
        Timer(cmd, globals=globals())
        .adaptive_autorange(min_run_time=1.0, max_run_time=20.0)
        .median
        * 1000
    )
    print(f"{cmd}: {median: 4.4f} ms")
    return median


# A tensor in pageable memory
pageable_tensor = torch.randn(1_000_000)

# A tensor in page-locked (pinned) memory
pinned_tensor = torch.randn(1_000_000, pin_memory=True)

# Runtimes:
pageable_to_device = timer("pageable_tensor.to('cuda:0')")
pinned_to_device = timer("pinned_tensor.to('cuda:0')")
pin_mem = timer("pageable_tensor.pin_memory()")
pin_mem_to_device = timer("pageable_tensor.pin_memory().to('cuda:0')")

# Ratios:
r1 = pinned_to_device / pageable_to_device
r2 = pin_mem_to_device / pageable_to_device

# Create a figure with the results
fig, ax = plt.subplots()

xlabels = [0, 1, 2]
bar_labels = [
    "pageable_tensor.to(device) (1x)",
    f"pinned_tensor.to(device) ({r1:4.2f}x)",
    f"pageable_tensor.pin_memory().to(device) ({r2:4.2f}x)"
    f"\npin_memory()={100*pin_mem/pin_mem_to_device:.2f}% of runtime.",
]
values = [pageable_to_device, pinned_to_device, pin_mem_to_device]
colors = ["tab:blue", "tab:red", "tab:orange"]
ax.bar(xlabels, values, label=bar_labels, color=colors)

ax.set_ylabel("Runtime (ms)")
ax.set_title("Device casting runtime (pin-memory)")
ax.set_xticks([])
ax.legend()

plt.show()

# Clear tensors
del pageable_tensor, pinned_tensor
_ = gc.collect()
Device casting runtime (pin-memory)
pageable_tensor.to('cuda:0'):  0.4667 ms
pinned_tensor.to('cuda:0'):  0.3703 ms
pageable_tensor.pin_memory():  0.3607 ms
pageable_tensor.pin_memory().to('cuda:0'):  0.7238 ms

我们可以观察到,将固定内存张量转换为GPU确实比可分页张量快得多,因为在底层,可分页张量必须先复制到固定内存,然后才能发送到GPU。

然而,与一些常见的看法相反,在将可分页的张量转换为GPU之前调用pin_memory()并不会带来任何显著的加速,相反,这个调用通常比直接执行传输要慢。这是有道理的,因为我们实际上是在要求Python执行一个操作,而这个操作CUDA在将数据从主机复制到设备之前无论如何都会执行。

注意

PyTorch 实现的 pin_memory 依赖于通过 cudaHostAlloc 在固定内存中创建一个全新的存储,在极少数情况下,可能比像 cudaMemcpy 那样分块传输数据更快。 同样,观察结果可能会因可用硬件、发送的张量大小或可用 RAM 的数量而有所不同。

non_blocking=True

如前所述,许多PyTorch操作可以通过non_blocking参数选择与主机异步执行。

在这里,为了准确评估使用non_blocking的好处,我们将设计一个稍微复杂一些的实验,因为我们想要评估在调用和不调用non_blocking的情况下,将多个张量发送到GPU的速度。

# A simple loop that copies all tensors to cuda
def copy_to_device(*tensors):
    result = []
    for tensor in tensors:
        result.append(tensor.to("cuda:0"))
    return result


# A loop that copies all tensors to cuda asynchronously
def copy_to_device_nonblocking(*tensors):
    result = []
    for tensor in tensors:
        result.append(tensor.to("cuda:0", non_blocking=True))
    # We need to synchronize
    torch.cuda.synchronize()
    return result


# Create a list of tensors
tensors = [torch.randn(1000) for _ in range(1000)]
to_device = timer("copy_to_device(*tensors)")
to_device_nonblocking = timer("copy_to_device_nonblocking(*tensors)")

# Ratio
r1 = to_device_nonblocking / to_device

# Plot the results
fig, ax = plt.subplots()

xlabels = [0, 1]
bar_labels = [f"to(device) (1x)", f"to(device, non_blocking=True) ({r1:4.2f}x)"]
colors = ["tab:blue", "tab:red"]
values = [to_device, to_device_nonblocking]

ax.bar(xlabels, values, label=bar_labels, color=colors)

ax.set_ylabel("Runtime (ms)")
ax.set_title("Device casting runtime (non-blocking)")
ax.set_xticks([])
ax.legend()

plt.show()
Device casting runtime (non-blocking)
copy_to_device(*tensors):  25.1154 ms
copy_to_device_nonblocking(*tensors):  19.2452 ms

为了更好地理解这里发生了什么,让我们来分析这两个函数:

from torch.profiler import profile, ProfilerActivity


def profile_mem(cmd):
    with profile(activities=[ProfilerActivity.CPU]) as prof:
        exec(cmd)
    print(cmd)
    print(prof.key_averages().table(row_limit=10))

让我们首先看看常规的 to(device) 调用堆栈:

print("Call to `to(device)`", profile_mem("copy_to_device(*tensors)"))
copy_to_device(*tensors)
-------------------------  ------------  ------------  ------------  ------------  ------------  ------------
                     Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg    # of Calls
-------------------------  ------------  ------------  ------------  ------------  ------------  ------------
                 aten::to         3.75%       1.167ms       100.00%      31.089ms      31.089us          1000
           aten::_to_copy        13.71%       4.262ms        96.25%      29.922ms      29.922us          1000
      aten::empty_strided        25.21%       7.838ms        25.21%       7.838ms       7.838us          1000
              aten::copy_        19.17%       5.960ms        57.33%      17.822ms      17.822us          1000
          cudaMemcpyAsync        19.18%       5.962ms        19.18%       5.962ms       5.962us          1000
    cudaStreamSynchronize        18.98%       5.901ms        18.98%       5.901ms       5.901us          1000
-------------------------  ------------  ------------  ------------  ------------  ------------  ------------
Self CPU time total: 31.089ms

Call to `to(device)` None

现在是 non_blocking 版本:

print(
    "Call to `to(device, non_blocking=True)`",
    profile_mem("copy_to_device_nonblocking(*tensors)"),
)
copy_to_device_nonblocking(*tensors)
-------------------------  ------------  ------------  ------------  ------------  ------------  ------------
                     Name    Self CPU %      Self CPU   CPU total %     CPU total  CPU time avg    # of Calls
-------------------------  ------------  ------------  ------------  ------------  ------------  ------------
                 aten::to         4.47%       1.023ms        99.90%      22.875ms      22.875us          1000
           aten::_to_copy        16.00%       3.664ms        95.43%      21.851ms      21.851us          1000
      aten::empty_strided        32.26%       7.386ms        32.26%       7.386ms       7.386us          1000
              aten::copy_        22.86%       5.235ms        47.17%      10.801ms      10.801us          1000
          cudaMemcpyAsync        24.31%       5.566ms        24.31%       5.566ms       5.566us          1000
    cudaDeviceSynchronize         0.10%      23.144us         0.10%      23.144us      23.144us             1
-------------------------  ------------  ------------  ------------  ------------  ------------  ------------
Self CPU time total: 22.898ms

Call to `to(device, non_blocking=True)` None

毫无疑问,使用non_blocking=True时结果更好,因为所有传输都在主机端同时启动,并且只进行一次同步。

好处将根据张量的数量和大小以及所使用的硬件而有所不同。

注意

有趣的是,阻塞的 to("cuda") 实际上执行了与 non_blocking=True 相同的异步设备转换操作 (cudaMemcpyAsync),只是在每次复制后有一个同步点。

协同效应

既然我们已经指出,将已经在固定内存中的张量数据传输到GPU比从可分页内存传输更快,并且我们知道异步执行这些传输也比同步更快,我们可以对这些方法的组合进行基准测试。首先,让我们编写几个新函数,这些函数将在每个张量上调用pin_memoryto(device)

def pin_copy_to_device(*tensors):
    result = []
    for tensor in tensors:
        result.append(tensor.pin_memory().to("cuda:0"))
    return result


def pin_copy_to_device_nonblocking(*tensors):
    result = []
    for tensor in tensors:
        result.append(tensor.pin_memory().to("cuda:0", non_blocking=True))
    # We need to synchronize
    torch.cuda.synchronize()
    return result

使用pin_memory()的好处对于较大的大批量张量更为明显:

tensors = [torch.randn(1_000_000) for _ in range(1000)]
page_copy = timer("copy_to_device(*tensors)")
page_copy_nb = timer("copy_to_device_nonblocking(*tensors)")

tensors_pinned = [torch.randn(1_000_000, pin_memory=True) for _ in range(1000)]
pinned_copy = timer("copy_to_device(*tensors_pinned)")
pinned_copy_nb = timer("copy_to_device_nonblocking(*tensors_pinned)")

pin_and_copy = timer("pin_copy_to_device(*tensors)")
pin_and_copy_nb = timer("pin_copy_to_device_nonblocking(*tensors)")

# Plot
strategies = ("pageable copy", "pinned copy", "pin and copy")
blocking = {
    "blocking": [page_copy, pinned_copy, pin_and_copy],
    "non-blocking": [page_copy_nb, pinned_copy_nb, pin_and_copy_nb],
}

x = torch.arange(3)
width = 0.25
multiplier = 0


fig, ax = plt.subplots(layout="constrained")

for attribute, runtimes in blocking.items():
    offset = width * multiplier
    rects = ax.bar(x + offset, runtimes, width, label=attribute)
    ax.bar_label(rects, padding=3, fmt="%.2f")
    multiplier += 1

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel("Runtime (ms)")
ax.set_title("Runtime (pin-mem and non-blocking)")
ax.set_xticks([0, 1, 2])
ax.set_xticklabels(strategies)
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
ax.legend(loc="upper left", ncols=3)

plt.show()

del tensors, tensors_pinned
_ = gc.collect()
Runtime (pin-mem and non-blocking)
copy_to_device(*tensors):  616.7664 ms
copy_to_device_nonblocking(*tensors):  544.0807 ms
copy_to_device(*tensors_pinned):  371.0937 ms
copy_to_device_nonblocking(*tensors_pinned):  345.8835 ms
pin_copy_to_device(*tensors):  996.5177 ms
pin_copy_to_device_nonblocking(*tensors):  677.9741 ms

其他复制方向(GPU -> CPU, CPU -> MPS)

到目前为止,我们一直假设从CPU到GPU的异步复制是安全的。这通常是正确的,因为CUDA会自动处理同步,以确保在读取时访问的数据是有效的。然而,这种保证并不适用于从GPU到CPU的传输。如果没有显式的同步,这些传输无法保证在数据访问时复制已经完成。因此,主机上的数据可能不完整或不正确,实际上使其成为垃圾数据:

tensor = (
    torch.arange(1, 1_000_000, dtype=torch.double, device="cuda")
    .expand(100, 999999)
    .clone()
)
torch.testing.assert_close(
    tensor.mean(), torch.tensor(500_000, dtype=torch.double, device="cuda")
), tensor.mean()
try:
    i = -1
    for i in range(100):
        cpu_tensor = tensor.to("cpu", non_blocking=True)
        torch.testing.assert_close(
            cpu_tensor.mean(), torch.tensor(500_000, dtype=torch.double)
        )
    print("No test failed with non_blocking")
except AssertionError:
    print(f"{i}th test failed with non_blocking. Skipping remaining tests")
try:
    i = -1
    for i in range(100):
        cpu_tensor = tensor.to("cpu", non_blocking=True)
        torch.cuda.synchronize()
        torch.testing.assert_close(
            cpu_tensor.mean(), torch.tensor(500_000, dtype=torch.double)
        )
    print("No test failed with synchronize")
except AssertionError:
    print(f"One test failed with synchronize: {i}th assertion!")
0th test failed with non_blocking. Skipping remaining tests
No test failed with synchronize

同样的考虑适用于从CPU到非CUDA设备(如MPS)的复制。 通常,只有在目标是支持CUDA的设备时,异步复制到设备才是安全的,无需显式同步。

总之,在使用non_blocking=True时,从CPU复制数据到GPU是安全的,但对于任何其他方向, non_blocking=True仍然可以使用,但用户必须确保在访问数据之前执行设备同步。

实用建议

我们现在可以根据我们的观察总结一些早期建议:

一般来说,non_blocking=True 会提供良好的吞吐量,无论原始张量是否在固定内存中。 如果张量已经在固定内存中,传输可以加速,但从 Python 主线程手动将其发送到固定内存是主机上的阻塞操作,因此会大大削弱使用 non_blocking=True 的好处(因为 CUDA 无论如何都会进行 pin_memory 传输)。

现在人们可能会合理地问,pin_memory() 方法有什么用途。 在接下来的部分中,我们将进一步探讨如何使用它来进一步加速数据传输。

其他注意事项

众所周知,PyTorch 提供了一个 DataLoader 类,其构造函数接受一个 pin_memory 参数。 考虑到我们之前关于 pin_memory 的讨论,你可能会想知道,如果内存固定本质上是阻塞的,那么 DataLoader 是如何加速数据传输的。

关键在于DataLoader使用一个单独的线程来处理数据从可分页内存到固定内存的传输,从而防止主线程中的任何阻塞。

为了说明这一点,我们将使用同名库中的TensorDict原语。 当调用to()时,默认行为是异步将张量发送到设备, 随后调用一次torch.device.synchronize()

此外,TensorDict.to() 包含一个 non_blocking_pin 选项,该选项在继续执行 to(device) 之前启动多个线程来执行 pin_memory()。这种方法可以进一步加速数据传输,如下例所示。

from tensordict import TensorDict
import torch
from torch.utils.benchmark import Timer
import matplotlib.pyplot as plt

# Create the dataset
td = TensorDict({str(i): torch.randn(1_000_000) for i in range(1000)})

# Runtimes
copy_blocking = timer("td.to('cuda:0', non_blocking=False)")
copy_non_blocking = timer("td.to('cuda:0')")
copy_pin_nb = timer("td.to('cuda:0', non_blocking_pin=True, num_threads=0)")
copy_pin_multithread_nb = timer("td.to('cuda:0', non_blocking_pin=True, num_threads=4)")

# Rations
r1 = copy_non_blocking / copy_blocking
r2 = copy_pin_nb / copy_blocking
r3 = copy_pin_multithread_nb / copy_blocking

# Figure
fig, ax = plt.subplots()

xlabels = [0, 1, 2, 3]
bar_labels = [
    "Blocking copy (1x)",
    f"Non-blocking copy ({r1:4.2f}x)",
    f"Blocking pin, non-blocking copy ({r2:4.2f}x)",
    f"Non-blocking pin, non-blocking copy ({r3:4.2f}x)",
]
values = [copy_blocking, copy_non_blocking, copy_pin_nb, copy_pin_multithread_nb]
colors = ["tab:blue", "tab:red", "tab:orange", "tab:green"]

ax.bar(xlabels, values, label=bar_labels, color=colors)

ax.set_ylabel("Runtime (ms)")
ax.set_title("Device casting runtime")
ax.set_xticks([])
ax.legend()

plt.show()
Device casting runtime
td.to('cuda:0', non_blocking=False):  619.8487 ms
td.to('cuda:0'):  542.9433 ms
td.to('cuda:0', non_blocking_pin=True, num_threads=0):  658.6780 ms
td.to('cuda:0', non_blocking_pin=True, num_threads=4):  360.2737 ms

在这个例子中,我们正在将许多大型张量从CPU传输到GPU。 这种情况非常适合利用多线程的pin_memory(),这可以显著提高性能。 然而,如果张量很小,多线程的开销可能会超过其带来的好处。 同样,如果只有少数张量,将张量固定在单独线程上的优势也会变得有限。

另外需要注意的是,虽然在固定内存中创建永久缓冲区以在将张量传输到GPU之前从可分页内存中传输张量可能看起来有优势,但这种策略并不一定会加快计算速度。将数据复制到固定内存中引起的固有瓶颈仍然是一个限制因素。

此外,将驻留在磁盘上的数据(无论是在共享内存还是文件中)传输到GPU通常需要将数据复制到固定内存(位于RAM中)的中间步骤。在这种情况下,利用非阻塞进行大数据传输可能会显著增加RAM消耗,可能导致不利影响。

在实践中,没有一种适用于所有情况的解决方案。 使用多线程pin_memory结合non_blocking传输的效果取决于多种因素,包括特定的系统、操作系统、硬件以及执行任务的性质。 以下是在尝试加速CPU和GPU之间的数据传输或比较不同场景下的吞吐量时需要检查的因素列表:

  • 可用核心数

    有多少个CPU核心可用?系统是否与其他可能竞争资源的用户或进程共享?

  • 核心利用率

    CPU核心是否被其他进程大量占用?应用程序是否在数据传输的同时执行其他CPU密集型任务?

  • 内存利用率

    当前使用了多少可分页和页面锁定的内存?是否有足够的空闲内存来分配额外的固定内存而不影响系统性能?请记住,没有什么是免费的,例如pin_memory将消耗RAM并可能影响其他任务。

  • CUDA设备能力

    GPU是否支持多个DMA引擎以进行并发数据传输?所使用的CUDA设备的具体功能和限制是什么?

  • 要发送的张量数量

    在典型操作中传输了多少个张量?

  • 要发送的张量的大小

    传输的张量大小是多少?几个大张量或许多小张量可能不会从相同的传输程序中受益。

  • 系统架构

    系统的架构如何影响数据传输速度(例如,总线速度、网络延迟)?

此外,在固定内存中分配大量张量或大型张量可能会独占RAM的很大一部分。 这会减少其他关键操作(如分页)的可用内存,从而可能对算法的整体性能产生负面影响。

结论

在本教程中,我们探讨了将张量从主机发送到设备时影响传输速度和内存管理的几个关键因素。我们了解到,使用non_blocking=True通常可以加速数据传输,而pin_memory()如果正确实施,也可以提高性能。然而,这些技术需要仔细的设计和校准才能有效。

请记住,分析您的代码并密切关注内存消耗对于优化资源使用和实现最佳性能至关重要。

其他资源

如果您在使用CUDA设备时遇到内存复制问题,或想了解更多关于本教程中讨论的内容,请查看以下参考资料:

脚本总运行时间: (1 分钟 17.533 秒)

Gallery generated by Sphinx-Gallery

优云智算