我正在使用tensorflow,我想通过同时使用CPU和一个GPU来加速预先训练的Keras模型的预测阶段(我对训练阶段不感兴趣)。
我试图创建两个不同的线程来提供两个不同的tensorflow会话(一个运行在CPU上,另一个运行在GPU上)。每个线程在一个循环中提供固定数量的批处理(例如,如果我们总共有100个批处理,我想为CPU分配20个批处理,在GPU上分配80个批处理,或者两者的任何可能组合),并组合结果。最好是自动分割。
然而,即使在这种情况下,批处理似乎是以同步方式馈送的,因为即使向CPU发送少量批处理并计算GPU中的所有其他批处理(以GPU为瓶颈),我观察到,对于仅使用GPU进行的测试,总的预测时间总是更高。
我希望它更快,因为当只有GPU工作时,CPU使用率大约为20-30%,因此有一些CPU可用于加快计算速度。
我读了很多讨论,但它们都涉及多个GPU的并行性,而不是GPU和CPU之间的并行性。
下面是我编写的代码示例:通过这种方式从同一个Keras模型加载tensor_cpu
和tensor_gpu
对象:
with tf.device('/gpu:0'):
model_gpu = load_model('model1.h5')
tensor_gpu = model_gpu(x)
with tf.device('/cpu:0'):
model_cpu = load_model('model1.h5')
tensor_cpu = model_cpu(x)
然后进行如下预测:
def predict_on_device(session, predict_tensor, batches):
for batch in batches:
session.run(predict_tensor, feed_dict={x: batch})
def split_cpu_gpu(batches, num_batches_cpu, tensor_cpu, tensor_gpu):
session1 = tf.Session(config=tf.ConfigProto(log_device_placement=True))
session1.run(tf.global_variables_initializer())
session2 = tf.Session(config=tf.ConfigProto(log_device_placement=True))
session2.run(tf.global_variables_initializer())
coord = tf.train.Coordinator()
t_cpu = Thread(target=predict_on_device, args=(session1, tensor_cpu, batches[:num_batches_cpu]))
t_gpu = Thread(target=predict_on_device, args=(session2, tensor_gpu, batches[num_batches_cpu:]))
t_cpu.start()
t_gpu.start()
coord.join([t_cpu, t_gpu])
session1.close()
session2.close()
如何实现这种CPU/GPU并行化?我想我错过了什么。
任何形式的帮助将非常感谢!
目前没有回答
相关问题 更多 >
编程相关推荐