分布式 multiprocessing.Pool#
Ray 支持使用 Ray Actor 而非本地进程运行使用 multiprocessing.Pool API 的分布式 Python 程序。这使得将使用 multiprocessing.Pool
的现有应用从单个节点轻松扩展到集群成为可能。
快速入门#
要开始使用,首先安装 Ray,然后使用 ray.util.multiprocessing.Pool
替代 multiprocessing.Pool
。这将首次创建 Pool
时启动一个本地 Ray 集群,并将您的任务分配到该集群上。有关如何在多节点 Ray 集群上运行的说明,请参阅下面的在集群上运行部分。
from ray.util.multiprocessing import Pool
def f(index):
return index
pool = Pool()
for result in pool.map(f, range(100)):
print(result)
目前支持完整的 multiprocessing.Pool
API。详情请参阅 multiprocessing 文档。
警告
使用 Ray 时,Pool
构造函数中的 context
参数将被忽略。
在集群上运行#
本节假设您已有一个正在运行的 Ray 集群。要启动 Ray 集群,请参阅集群设置说明。
要将 Pool
连接到正在运行的 Ray 集群,您可以通过以下两种方式之一指定头节点的地址:
设置
RAY_ADDRESS
环境变量。将
ray_address
关键字参数传递给Pool
构造函数。
from ray.util.multiprocessing import Pool
# Starts a new local Ray cluster.
pool = Pool()
# Connects to a running Ray cluster, with the current node as the head node.
# Alternatively, set the environment variable RAY_ADDRESS="auto".
pool = Pool(ray_address="auto")
# Connects to a running Ray cluster, with a remote node as the head node.
# Alternatively, set the environment variable RAY_ADDRESS="<ip_address>:<port>".
pool = Pool(ray_address="<ip_address>:<port>")
您也可以在创建 Pool
之前手动调用 ray.init()
(并使用任何支持的配置选项) 来启动 Ray。