分布式 multiprocessing.Pool#
Ray 支持使用 Ray Actors 而非本地进程来运行分布式 Python 程序,并且支持 multiprocessing.Pool API。这使得现有的使用 multiprocessing.Pool 的应用程序可以轻松地从单节点扩展到集群。
快速入门#
开始之前,请先 安装 Ray,然后将 multiprocessing.Pool 替换为 ray.util.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。