我想在 Pytorch 中使用 CUDA 流来并行一些计算,但我不知道该怎么做。例如,如果有 2 个任务 A 和 B 需要并行化,我想做以下事情:
stream0 = torch.get_stream()
stream1 = torch.get_stream()
with torch.now_stream(stream0):
// task A
with torch.now_stream(stream1):
// task B
torch.synchronize()
// get A and B's answer
Run Code Online (Sandbox Code Playgroud)
如何在真正的 python 代码中实现目标?
小智 13
s1 = torch.cuda.Stream()
s2 = torch.cuda.Stream()
# Initialise cuda tensors here. E.g.:
A = torch.rand(1000, 1000, device = ‘cuda’)
B = torch.rand(1000, 1000, device = ‘cuda’)
# Wait for the above tensors to initialise.
torch.cuda.synchronize()
with torch.cuda.stream(s1):
C = torch.mm(A, A)
with torch.cuda.stream(s2):
D = torch.mm(B, B)
# Wait for C and D to be computed.
torch.cuda.synchronize()
# Do stuff with C and D.
Run Code Online (Sandbox Code Playgroud)