模式:使用 ray.wait 限制待处理任务的数量#
在此模式中,我们使用 ray.wait()
来限制待处理任务的数量。
如果我们持续提交任务的速度快于它们的处理时间,我们将积累任务在待处理任务队列中,这最终可能导致 OOM。使用 ray.wait()
,我们可以应用背压并限制待处理任务的数量,这样待处理任务队列就不会无限增长并导致 OOM。
注意
如果我们提交的任务数量是有限的,不太可能遇到上面提到的问题,因为每个任务只需要队列中少量用于记账的内存。这更有可能发生在我们有无限的任务流需要运行时。
注意
此方法主要用于限制同时处于“飞行中”的任务数量。它也可以用于限制同时运行的任务数量,但不推荐,因为它会损害调度性能。Ray 会根据资源可用性自动决定任务并行度,因此调整同时运行任务数量的推荐方法是修改每个任务的资源需求。
示例用例#
您有一个工作 actor,它以每秒 X 个任务的速度处理任务,您希望以低于 X 的速度向其提交任务以避免 OOM。
例如,Ray Serve 使用此模式来限制每个 worker 的待处理查询数量。
限制待处理任务数量#
代码示例#
无背压
import ray
ray.init()
@ray.remote
class Actor:
async def heavy_compute(self):
# taking a long time...
# await asyncio.sleep(5)
return
actor = Actor.remote()
NUM_TASKS = 1000
result_refs = []
# When NUM_TASKS is large enough, this will eventually OOM.
for _ in range(NUM_TASKS):
result_refs.append(actor.heavy_compute.remote())
ray.get(result_refs)
有背压
MAX_NUM_PENDING_TASKS = 100
result_refs = []
for _ in range(NUM_TASKS):
if len(result_refs) > MAX_NUM_PENDING_TASKS:
# update result_refs to only
# track the remaining tasks.
ready_refs, result_refs = ray.wait(result_refs, num_returns=1)
ray.get(ready_refs)
result_refs.append(actor.heavy_compute.remote())
ray.get(result_refs)