目标是在所有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上。
这其实很短,不应该占用很多资源。
有人知道怎么解决这个问题吗?