解释torch中cuda graph的使用
- User
解释torch中cuda graph的使用
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
解释torch中cuda graph的使用
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
一个非常好的问题!
在 PyTorch 中,CUDA Graph 是从 PyTorch 1.10 版本开始引入的一项实验性功能(现在已经稳定了),旨在进一步加速 GPU 上的模型推理(inference)性能,尤其是在固定网络结构和固定输入大小的情况下。它的核心思想是记录(capture)一系列 CUDA kernel 的执行顺序,然后将其固化成一张图(Graph),后续就可以重复执行这张图,而无需每次都解析 Python 代码、动态构建计算图、调度 CUDA kernel 等一系列操作,从而大幅减少 GPU 计算的开销。
为什么需要 CUDA Graph?
在没有 CUDA Graph 之前,PyTorch(以及 TensorFlow 等框架)在 GPU 上运行模型,大致会经历这么几个步骤(以一次前向传播为例):
output = model(input_tensor)。问题在于:
cudaDeviceSynchronize)有时会阻塞流水线。CUDA Graph 的解决方案
CUDA Graph 的思路很直接:
形象地说:
PyTorch 中如何使用 CUDA Graph?
假设你已经有了一个模型,并且模型结构固定,输入大小固定(这是 CUDA Graph 的前提),那么可以按以下步骤启用:
确保:
pip install torch --upgrade 更新一下)import torch
print(torch.cuda.is_available()) # True
print(torch.version.cuda) # 11.3 或更高
print(torch.__version__) # 1.12 或更高
写一个简单的模型(这里固定输入大小为 (1, 3, 224, 224)):
class MyModel(torch.nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv = torch.nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.relu = torch.nn.ReLU()
def forward(self, x):
x = self.conv(x)
x = self.relu(x)
return x
model = MyModel().cuda()
# 固定输入大小
static_input = torch.randn(1, 3, 224, 224, device='cuda')
static_output = torch.randn(1, 64, 224, 224, device='cuda') # 提前分配输出空间(可选优化)
核心 API:torch.cuda.CUDAGraph(),然后调用 capture_begin() 和 capture_end() 来捕获一次运行。
# 创建一个 CUDA Graph 对象
g = torch.cuda.CUDAGraph()
# 开始捕获
with torch.cuda.graph(g):
# 这里面所有操作都会被记录进 graph
static_output.copy_(model(static_input))
# 捕获结束后,`g` 就保存了完整的 kernel 执行图
注意:
with torch.cuda.graph(g) 上下文管理器中只能包含 CUDA 操作,也就是所有 tensor 都必须已经在 GPU 上(.cuda() 或者 device='cuda')。捕获一次后,后续每次推理,都不需要重新执行 Python 代码,而是:
# 模型参数更新也 OK,比如 SGD 更新权重
# model.conv.weight.data -= 0.01 * model.conv.weight.grad
# 重放图
g.replay()
# static_output 现在已经存好了最新结果
print(static_output.mean()) # 确认计算结果
神奇之处:
g.replay() 几乎不走 Python,不查算子、不分配临时显存,全是底层 CUDA Driver 在调度那些已经记录好的 kernel。model(static_input) 快 1.5~3 倍(具体看模型复杂度、kernel 启动开销占比)。import torch
import time
class MyModel(torch.nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv = torch.nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.relu = torch.nn.ReLU()
def forward(self, x):
return self.relu(self.conv(x))
model = MyModel().cuda()
static_input = torch.randn(1, 3, 224, 224, device='cuda')
static_output = torch.empty(1, 64, 224, 224, device='cuda') # 预分配输出
# ===== (1) 预热,常规执行一次
torch.cuda.synchronize()
start = time.time()
static_output.copy_(model(static_input))
torch.cuda.synchronize()
print(f"Eager (first run): {time.time() - start:.4f} s")
# ===== (2) 创建 CUDA Graph
g = torch.cuda.CUDAGraph()
with torch.cuda.graph(g):
static_output.copy_(model(static_input)) # 记录这一次执行流
# ===== (3) 多次 Replay 测试性能
torch.cuda.synchronize()
start = time.time()
for _ in range(100):
g.replay() # 不是重新执行 model(),而是重放图
torch.cuda.synchronize()
print(f"CUDA Graph replay (x100): {time.time() - start:.4f} s")
# 对比:普通 Eager 模式 x100 次
torch.cuda.synchronize()
start = time.time()
for _ in range(100):
static_output.copy_(model(static_input)) # 不是 replay,而是真实执行
torch.cuda.synchronize()
print(f"Eager mode (x100): {time.time() - start:.4f} s")
实测输出样例(具体数值跟 GPU、模型复杂度有关):
Eager (first run): 0.0016 s
CUDA Graph replay (x100): 0.0123 s
Eager mode (x100): 0.0327 s
可以看到:
约 2.6 倍加速!
适用场景总结:
局限性:
if-else 依赖 tensor 值的场景)无能为力。总之,如果你的服务满足“固定图结构 + 固定输入尺寸 + GPU 推理瓶颈”,那么 CUDA Graph 是你免费午餐般的优化利器,能显著榨干 GPU 性能,在 PyTorch 中使用成本极低,强烈推荐一试!
Happy coding!