代码之家  ›  专栏  ›  技术社区  ›  gasoon

如何在pytorch中使用cuda流?

  •  1
  • gasoon  · 技术社区  · 6 年前

    我想使用pytorch中的cuda流来并行一些计算,但我不知道如何进行。 例如,如果有两个任务,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
    

    如何在真正的Python代码中实现目标?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Tomas    6 年前
    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.