代码之家  ›  专栏  ›  技术社区  ›  ZHANG Juenjie

急执行与多处理不兼容

  •  0
  • ZHANG Juenjie  · 技术社区  · 6 年前

    目标是在所有GPU上分配工作。然而,我发现这不能用多重处理来完成。

    下面是代码(除了一些额外的工作外,代码确实很短):

    import os,sys
    import multiprocessing
    import numpy as np
    # clear folder
    folder = os.getcwd()+'/temp/'
    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        if os.path.isfile(file_path):
            os.unlink(file_path)
    
    # process
    p={}
    n_batches=4
    
    # kernel to be called in each process
    # here, the example is just to return i_batch
    def kernel(i_batch):
        import tensorflow as tf
        from tensorflow.python.eager.context import context, EAGER_MODE, GRAPH_MODE
        def switch_to(mode):
            ctx = context()._eager_context
            ctx.mode = mode
            ctx.is_eager = mode == EAGER_MODE
        switch_to(EAGER_MODE)
        assert tf.executing_eagerly()
    
        with tf.device("GPU:"+str(i_batch)):
            tf.tile([1],[10])
            r=tf.constant(i_batch).numpy()
        return r
    
    # multiprocessing loop
    for i_batch in range(n_batches):
        def multi_processing():
            result=kernel(i_batch)
            np.save(os.getcwd()+'/temp/result'+str(i_batch), result)
    
        # start multi-processing to allocate     
        p[i_batch] = multiprocessing.Process(target=multi_processing)
        p[i_batch].daemon = True
        p[i_batch].start()
    
    # wait
    for i_batch in range(n_batches):   
        p[i_batch].join()
    
    result=0.
    for i_batch in range(n_batches): 
        result+=np.load(os.getcwd()+'/temp/result'+str(i_batch)+'.npy')
    result
    

    函数内核将由主循环调用,主循环将工作分配到四个gpu上。

    这其实很短,不应该占用很多资源。

    有人知道怎么解决这个问题吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   kvish    6 年前

    参考文献: https://stackoverflow.com/a/34514932/10111931

    如果你看看 GPUOptions

    您可以尝试的第二件事是使用CUDA\u VISIBLE\u DEVICES选项,让每个进程只使用GPU的一个子集进行操作。 参考文献: https://stackoverflow.com/a/37901914/10111931