使用 Ray 并行化大型程序的正确方法

Pat*_*l75 2 python memory-management shared-memory redis ray

我有一个相当大的 Python 程序(约 800 行),其结构如下:

  • 设置说明,我在其中处理用户提供的输入文件并定义对程序执行全局的变量/对象。
  • 主函数,它利用之前的设置阶段并调用程序的主要附加函数。
  • 附加函数可以是主要函数,即它们由主函数直接调用,也可以是次要函数,即它们仅由主要附加函数调用。
  • 我处理主函数结果的最后几行代码。

该程序是大规模并行的,因为主函数的每次执行都独立于前一个和下一个函数。因此,我使用 Ray 在集群中的多个工作节点上并行执行主函数。操作系统为 CentOS Linux 版本 8.2.2004(Core),集群执行 PBS Pro 19.2.4.20190830141245。我使用的是 Python 3.7.4、Ray 0.8.7 和 Redis 3.4.1。

我的Python脚本中有以下内容,foo主要函数在哪里:

@ray.remote(memory=2.5 * 1024 * 1024 * 1024)
def foo(locInd):
    # Main function

if __name__ == '__main__':
    ray.init(address='auto', redis_password=args.pw,
             driver_object_store_memory=10 * 1024 * 1024 * 1024)
    futures = [foo.remote(i) for i in zip(*np.asarray(indArr == 0).nonzero())]
    waitingIds = list(futures)
    while len(waitingIds) > 0:
        readyIds, waitingIds = ray.wait(
            waitingIds, num_returns=min([checkpoint, len(waitingIds)]))
        for r0, r1, r2, r3, r4, r5, r6, r7 in ray.get(readyIds):
            # Process results
            indArr[r0[::-1]] = 1
            nodesComplete += 1
    ray.shutdown()
Run Code Online (Sandbox Code Playgroud)

以下是我用来启动 Ray 的说明

# Head node
/path/to/ray start --head --port=6379 \
--redis-password=$redis_password \
--memory $((120 * 1024 * 1024 * 1024)) \
--object-store-memory $((20 * 1024 * 1024 * 1024)) \
--redis-max-memory $((10 * 1024 * 1024 * 1024)) \
--num-cpus 48 --num-gpus 0

# Worker nodes
/path/to/ray start --block --address=$1 \
--redis-password=$2 --memory $((120 * 1024 * 1024 * 1024)) \
--object-store-memory $((20 * 1024 * 1024 * 1024)) \
--redis-max-memory $((10 * 1024 * 1024 * 1024)) \
--num-cpus 48 --num-gpus 0
Run Code Online (Sandbox Code Playgroud)

只要我处理的数据集足够小,一切都会按预期运行。然而,执行会产生以下警告

  • 2020-08-17 17:16:44,289 警告worker.py:1134 --警告:腌制时远程函数的__main__.foo大小为220019409。它将存储在 Redis 中,这可能会导致内存问题。这可能意味着它的定义使用了一个大数组或其他对象。
  • 2020-08-17 17:17:10,281 警告worker.py:1134——该worker被要求执行一个它没有注册的函数。您可能必须重新启动 Ray。

如果我尝试在更大的数据集上运行代码,则会收到以下错误:

Traceback (most recent call last):
  File "/home/157/td5646/.local/lib/python3.7/site-packages/redis/connection.py", line 700, in send_packed_command
    sendall(self._sock, item)
  File "/home/157/td5646/.local/lib/python3.7/site-packages/redis/_compat.py", line 8, in sendall
2020-08-21 14:22:34,226 WARNING worker.py:1134 -- Warning: The remote function __main__.foo has size 898527351 when pickled. It will be stored in Redis, which could cause memory issues. This may mean that its definition uses a large array or other object.
    return sock.sendall(*args, **kwargs)
ConnectionResetError: [Errno 104] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./Program.py", line 1030, in <module>
    for i in zip(*np.asarray(indArr == 0).nonzero())]
  File "./Program.py", line 1030, in <listcomp>
    for i in zip(*np.asarray(indArr == 0).nonzero())]
  File "/home/157/td5646/.local/lib/python3.7/site-packages/ray/remote_function.py", line 95, in _remote_proxy
    return self._remote(args=args, kwargs=kwargs)
  File "/home/157/td5646/.local/lib/python3.7/site-packages/ray/remote_function.py", line 176, in _remote
    worker.function_actor_manager.export(self)
  File "/home/157/td5646/.local/lib/python3.7/site-packages/ray/function_manager.py", line 152, in export
    "max_calls": remote_function._max_calls
  File "/home/157/td5646/.local/lib/python3.7/site-packages/redis/client.py", line 3023, in hmset
    return self.execute_command('HMSET', name, *items)
  File "/home/157/td5646/.local/lib/python3.7/site-packages/redis/client.py", line 877, in execute_command
    conn.send_command(*args)
  File "/home/157/td5646/.local/lib/python3.7/site-packages/redis/connection.py", line 721, in send_command
    check_health=kwargs.get('check_health', True))
  File "/home/157/td5646/.local/lib/python3.7/site-packages/redis/connection.py", line 713, in send_packed_command
    (errno, errmsg))
redis.exceptions.ConnectionError: Error 104 while writing to socket. Connection reset by peer.
Run Code Online (Sandbox Code Playgroud)

显然,我向雷描述该程序的方式是错误的。我有 Scipy Interpolator 对象,我认为它们是全局的,但是,正如 GitHub线程中已经指出的那样,我应该调用ray.put它们。问题是我遇到了这些ValueError: buffer source array is read-only我不知道如何诊断的问题。另外,我不确定是否应该用主函数来装饰所有函数@ray.remote,还是只用主函数来装饰所有函数。我想我可以@ray.remote(num_cpus=1)对所有附加函数执行此操作,因为它实际上只应该是并行执行的主函数,但我不知道这是否有意义。

非常感谢任何帮助,如果需要,我很乐意提供更多信息。

Pat*_*l75 6

我可能已经解决了我的问题,但我不介意别人的意见,因为我的雷知识确实有限。另外,我想这可能会帮助其他遇到类似问题的人(希望我并不孤单!)。

正如我在问题中提到的,该程序对于足够小的数据集运行得相当好(尽管它似乎绕过了 Ray 逻辑的某些方面),但它最终在大型数据集上崩溃了。仅使用 Ray 任务,我无法调用存储在对象存储 ( ValueError: buffer source array is read-only) 中的 Scipy Interpolator 对象,并且装饰所有函数没有意义,因为实际上只有主函数应该同时执行(同时调用其他函数)。

因此,我决定更改程序的结构以使用 Ray Actors。设置说明现在是该__init__方法的一部分。特别是,Scipy Interpolator 对象在此方法中定义,并设置为 的属性self,就像全局变量一样。大多数函数(包括主函数)已成为类方法,但通过 Numba 编译的函数除外。对于后者,它们仍然是用 修饰的独立函数@jit,但它们现在在调用 jitted 函数的类中都有一个等效的包装方法。

为了让我的程序并行执行现在的 main 方法,我依赖 ActorPool。我创建与可用 CPU 一样多的 actor,每个 actor 执行 main 方法,成功调用方法和 Numba 编译的函数,同时还管理访问 Interpolator 对象。我只适用@ray.remote于定义的Python类。所有这些都转化为以下结构:

@ray.remote
class FooClass(object):
    def __init__(self, initArgs):
        # Initialisation

    @staticmethod
    def exampleStaticMethod(args):
        # Processing
        return

    def exampleMethod(self, args):
        # Processing
        return

    def exampleWrapperMethod(self, args):
        return numbaCompiledFunction(args)

    def mainMethod(self, poolMapArgs):
        # Processing
        return


@jit
def numbaCompiledFunction(args):
    # Processing
    return


ray.init(address='auto', redis_password=redPass)
actors = []
for actor in range(int(ray.cluster_resources()['CPU'])):
    actors.append(FooClass.remote(initArgs))
pool = ActorPool(actors)
for unpackedTuple in pool.map_unordered(
        lambda a, v: a.mainMethod.remote(v),
        poolMapArgs):
    # Processing
ray.shutdown()
Run Code Online (Sandbox Code Playgroud)

它在分布在 4 个节点上的 192 个 CPU 上成功运行,没有任何警告或错误。

  • 开始使用 ray 一个月了,这个例子确实很有帮助。多谢 (4认同)