反模式:一次性通过 ray.get 获取太多对象导致失败#

TLDR: 避免对过多对象调用 ray.get(),因为这会导致堆内存不足或对象存储空间不足。而是应批量获取和处理结果。

如果您有大量想要并行运行的任务,尝试一次性对所有任务进行 ray.get() 可能会导致堆内存不足或对象存储空间不足而失败,因为 Ray 需要同时将所有对象获取到调用者端。相反,您应该批量获取和处理结果。一旦处理完一批,Ray 就会逐出该批中的对象,为后续批次腾出空间。

../../_images/ray-get-too-many-objects.svg

一次性通过 ray.get() 获取太多对象#

代码示例#

反模式

import ray
import numpy as np

ray.init()


def process_results(results):
    # custom process logic
    pass


@ray.remote
def return_big_object():
    return np.zeros(1024 * 10)


NUM_TASKS = 1000

object_refs = [return_big_object.remote() for _ in range(NUM_TASKS)]
# This will fail with heap out-of-memory
# or object store out-of-space if NUM_TASKS is large enough.
results = ray.get(object_refs)
process_results(results)

更好的方法

BATCH_SIZE = 100

while object_refs:
    # Process results in the finish order instead of the submission order.
    ready_object_refs, object_refs = ray.wait(object_refs, num_returns=BATCH_SIZE)
    # The node only needs enough space to store
    # a batch of objects instead of all objects.
    results = ray.get(ready_object_refs)
    process_results(results)

这里除了批量获取以避免失败外,我们还使用 ray.wait() 按完成顺序而非提交顺序处理结果,以缩短运行时长。更多详情请参阅反模式:使用 ray.get 按提交顺序处理结果会增加运行时长