我想使用TF 2.0在我的GPU集群上运行分布式预测。我用MirroredStrategy训练了一个用凯拉斯制作的CNN,并保存了下来。我可以加载模型并对其使用.predict(),但我想知道这是否会自动使用可用的GPU进行分布式预测。如果不是,我如何运行分布式预测来加速推理并使用所有可用的GPU内存?
目前,当运行许多大型预测时,我超过了其中一个GPU(12 it )的内存(需要17 it),推理失败,因为它耗尽了内存:
Allocator (GPU_0_bfc) ran out of memory trying to allocate 1.12GiB但我有多个GPU,也想使用它们的内存。谢谢。
发布于 2021-02-03 02:58:26
我能够像下面这样拼凑出单工作者、多GPU的预测(就当它是一个草图吧--它使用的管道代码并不是普遍适用的,但它应该会给你一个模板供你参考):
# https://github.com/tensorflow/tensorflow/issues/37686
# https://www.tensorflow.org/tutorials/distribute/custom_training
def compute_and_write_ious_multi_gpu(path: str, filename_csv: str, include_sampled: bool):
strategy = tf.distribute.MirroredStrategy()
util.log('Number of devices: {}'.format(strategy.num_replicas_in_sync))
(ds, s, n) = dataset(path, shuffle=False, repeat=False, mask_as_input=True)
dist_ds = strategy.experimental_distribute_dataset(ds)
def predict_step(inputs):
images, labels = inputs
return model(images, training=False)
@tf.function
def distributed_predict_step(dataset_inputs):
per_replica_losses = strategy.run(predict_step, args=(dataset_inputs,))
return per_replica_losses # unwrap!?
# https://stackoverflow.com/questions/57549448/how-to-convert-perreplica-to-tensor
def unwrap(per_replica): # -> list of numpy arrays
if strategy.num_replicas_in_sync > 1:
out = per_replica.values
else:
out = (per_replica,)
return list(map(lambda x: x.numpy(), out))
with strategy.scope():
model = wrap_model()
util.log(f'Starting distributed prediction for {filename_csv}')
ious = [unwrap(distributed_predict_step(x)) for x in dist_ds]
t = ious
ious = [item for sublist in t for item in
sublist] # https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
util.log(f'Distributed prediction done for {filename_csv}')
ious = np.concatenate(ious).ravel().tolist()
ious = round_ious(ious)
ious = list(zip(ious, ds.all_image_paths))
ious.sort()
write_ious(ious, filename_csv, include_sampled)这确实在GPU之间分配了负载,但不幸的是,它们的利用率非常低-在我的特定情况下,相应的单GPU代码运行大约12小时,而这运行在7.7小时,所以即使是2倍的加速,尽管GPU的数量是8倍。
我认为这主要是一个数据馈送问题,但我不知道如何解决它。希望其他人能提供一些更好的见解?
https://stackoverflow.com/questions/62356736
复制相似问题