首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用Tensorflow进行分布式预测/推理

如何使用Tensorflow进行分布式预测/推理
EN

Stack Overflow用户
提问于 2020-06-13 15:21:00
回答 1查看 609关注 0票数 3

我想使用TF 2.0在我的GPU集群上运行分布式预测。我用MirroredStrategy训练了一个用凯拉斯制作的CNN,并保存了下来。我可以加载模型并对其使用.predict(),但我想知道这是否会自动使用可用的GPU进行分布式预测。如果不是,我如何运行分布式预测来加速推理并使用所有可用的GPU内存?

目前,当运行许多大型预测时,我超过了其中一个GPU(12 it )的内存(需要17 it),推理失败,因为它耗尽了内存:

代码语言:javascript
运行
复制
Allocator (GPU_0_bfc) ran out of memory trying to allocate 1.12GiB

但我有多个GPU,也想使用它们的内存。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-02-03 02:58:26

我能够像下面这样拼凑出单工作者、多GPU的预测(就当它是一个草图吧--它使用的管道代码并不是普遍适用的,但它应该会给你一个模板供你参考):

代码语言:javascript
运行
复制
# 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倍。

我认为这主要是一个数据馈送问题,但我不知道如何解决它。希望其他人能提供一些更好的见解?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62356736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档