python
import torch
import torch.cuda.graph as graph
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()
input_tensor = torch.randn(1, 3, 224, 224, device='cuda')
# 捕获 CUDA Graph
g = graph.CUDAGraph()
with graph.capture_begin(g):
output = model(input_tensor)
# 更新输入 tensor 的值
new_input_tensor = torch.randn(1, 3, 224, 224, device='cuda')
g.update_input(input_tensor, new_input_tensor)
# 重放 CUDA Graph
torch.cuda.synchronize()
start = time.time()
for _ in range(100):
g.replay()
torch.cuda.synchronize()
print(f"CUDA Graph replay (x100): {time.time() - start:.4f} s")