- 安装Ray
- If you are not using Anaconda, you need the following.
- Ray使用
- The value of the original
regular_function - Ray also supports fractional resource requirements
- Ray support custom resources too.
- Actors使用
- GPU支持
- 序列化
- 内存管理
- 调试和分析
- 高级用法
- !python
- cython: embedsignature=True, binding=True
- 最佳实践:Ray with Tensorflow
- 最佳实践:Ray with PyTorch
- Ray配置
- Ray部署
基于Ray-0.8.0文档翻译。详细信息请查看官方文档地址。
安装Ray
- Installing Ray with Anaconda
shell conda create --name ray conda activate ray conda install --name ray pip pip install ray可以通过pip list 查看ray是否安装成功
- Building Ray from Source> 对于一般用户通过pip安装就足够了,但是如果您需要也可以从源代码进行构建
在build ray之前,需要先安装如下依赖:```shell sudo apt-get update sudo apt-get install -y build-essential curl unzip psmisc
If you are not using Anaconda, you need the following.
sudo apt-get install python-dev # For Python 2. sudo apt-get install python3-dev # For Python 3.
pip install cython==0.29.0
<br />For MacOS用户,执行下面命令:```shellbrew updatebrew install wgetpip install cython==0.29.0
如果你在使用Anaconda,你可能需要执行:```shell
conda install libgcc
<br />Install Ray:```shellgit clone https://github.com/ray-project/ray.git# Install Bazel.ray/ci/travis/install-bazel.sh# Optionally build the dashboard (requires Node.js, see below for more information).pushd ray/python/ray/dashboard/clientnpm cinpm run buildpopd# Install Ray.cd ray/pythonpip install -e . --verbose # Add --user if you see a permission denied error.
Dashboard 支持
如果要使用仪表板,则在安装Ray之前,还需要安装Node.js来构建仪表板
使用仪表板还需要:
- Python 3
- aiohttp
- psutil
后面两个依赖可以通过pip进行安装:
pip install aiohttp psutil
安装后,可以通过在初始化期间设置include_webui = True来启用仪表板,即
import rayray.init(include_webui=True)
构建docker image
执行自带的脚步创建docker镜像:
cd ray./build-docker.sh
该脚步会创建如下几个镜像:
ray-project/deploy: 适合最终用户的完整的代码和二进制文件副本。ray-project/examples: 添加了用于运行示例的其他库。ray-project/base-deps: 该映像基于Ubuntu Xenial构建,并包含Anaconda和其他基本依赖项,可以作为开发人员的起点。
在docker里运行Ray
启动部署容器:
docker run --shm-size=<shm-size> -t -i ray-project/deploy
将替换为适合您的系统的资源限制,如512M、2G 使用-t和-i选项来支持容器的交互模式使用。 Note:Ray需要大量的共享内存,因为每个对象存储在共享内存中保存了其所有的对象,所以共享内存的容量会限制对象存储的大小
测试安装是否成功,通过执行git仓库下的脚本:
python -m pytest -v python/ray/tests/test_mini.py
Ray使用
Ray的核心概念:
- 使用远程函数(tasks)[ray.remote]
- 拉取结果(object IDs)[ray.put, ray.get, ray.wait]
- 使用远程类(actors)[ray.remote]
使用Ray,您的代码将在单台机器上运行,并且可以轻松地扩展到大型群集中。
远程函数(Tasks)
Ray允许任意Python函数异步执行。这些异步Ray函数称为“远程函数”。将Python函数转换为远程函数的标准方法是添加@ray.remote装饰器。例:
# A regular Python function.def regular_function():return 1# A Ray remote function.@ray.remotedef remote_function():return 1
和常规函数使用上的差别:
- 调用方式: 常规函数调用方式是:
regular_function(),Ray远程函数调用则为remote_function.remote() - 获取返回值:常规函数执行会立即返回结果值为1,而Ray远程函数执行立即返回的是对象ID(future)然后将创建task在worker进程上被执行。可以使用
ray.get获取结果。 ```python assert regular_function() == 1
object_id = remote_function.remote()
The value of the original regular_function
assert ray.get(object_id) == 1
3. 并行执行差异:常规函数调用是顺序执行的,而Ray远程函数调用是并行执行的。```python# These happen serially.for _ in range(4):regular_function()# These happen in parallel.for _ in range(4):remote_function.remote()
Note: 对象ID(Object IDs)也可以传递到远程函数中。当函数实际执行时,该参数将作为常规Python对象被接收。例如:
@ray.remotedef remote_chain_function(value):return value + 1y1_id = remote_function.remote()assert ray.get(y1_id) == 1chained_id = remote_chain_function.remote(y1_id)assert ray.get(chained_id) == 2
注意⚠️:
- 在第一个任务完成执行之前,第二个任务将不会执行,因为第二个任务取决于第一个任务的输出。简而言之:依赖任务是串行的
- 如果两个任务计划在不同的计算机上执行,则第一个任务的输出(与y1_id对应的值)将通过网络发送到计划第二个任务的计算机上。
通常,您可能需要指定任务的资源要求(例如,某个任务可能需要GPU资源)。ray.init()命令将自动检测机器上是否可用的GPUs和CPUs。不过你也可以通过传入特定的资源来改变选择如:ray.init(num_cpus=8, num_gpus=4, resources={'Custom': 2})
对于那些对CPU和GPU有特殊要求的任务,可以通过num_cpus和num_gpus参数指定。仅当机器有足够的CPU和GPU资源可用于执行任务时,任务才会被执行。Ray也支持处理任意的自定义资源。
Note:
- 如果未在
@ray.remote装饰器中指定任何资源,则默认值为1个CPU资源,没有其他资源. - 如果指定CPU,Ray不会强制执行隔离(即您的任务应满足这个请求)
- 如果指定GPU,Ray会以可见设备的形式提供隔离(设置环境变量CUDA_VISIBLE_DEVICES),但是实际使用GPUs是task的责任(例如,通过TensorFlow或PyTorch之类的深度学习框架)
任务的资源需求会影响Ray的调度并发。特别是,给定节点上所有同时执行的任务的资源需求总和不能超过节点的总资源。@ray.remote(num_cpus=4, num_gpus=2)def f():return 1
资源需求规范的更多示例: ```pythonRay also supports fractional resource requirements
@ray.remote(num_gpus=0.5) def h(): return 1
Ray support custom resources too.
@ray.remote(resources={‘Custom’: 1}) def f(): return 1
此外,远程函数可以返回多个对象ID(通过`num_return_vals`参数指定):```python@ray.remote(num_return_vals=3)def return_multiple():return 1, 2, 3a_id, b_id, c_id = return_multiple.remote()
Ray中的Objects
在Ray中,我们可以在对象上创建和计算。我们将这些对象称为远程对象,并且可以通过Object IDs进行引用。远程对象存储在共享内存对象存储中,并且群集中每个节点都有一个对象存储。在群集设置中,实际上我们可能不知道每个对象驻留在哪台计算机上。
对象ID本质上是唯一的ID,用于引用远程对象。如果您熟悉futures,在概念上和对象ID是相似的。可以通过多种方式来创建对象ID:
- 通过远程函数调用返回。
- 通过调用
ray.put返回y = 1object_id = ray.put(y)
put source: ```python ray.put(value, weakref=False) Store an object in the object store.
The object may not be evicted while a reference to the returned ID exists. Note that this pinning only applies to the particular object ID returned by put, not object IDs in general.
Parameters:
value – The Python object to be stored.
weakref – If set, allows the object to be evicted while a reference to the returned ID exists. You might want to set this if putting a lot of objects that you might not need in the future.
Returns:
The object ID assigned to this value.
**注意:** 远程对象是不可变的。也就是说,创建后不能更改其值。这允许将远程对象复制到多个对象存储中,而无需同步副本。<a name="f0218348"></a>### 拉取结果命令`ray.get(x_id, timeout=None)`将获得一个Object ID,并且从对应的远程对象创建出一个python对象。首先,如果当前节点的对象存储中不包含该对象,则下载对象。其次,如果对象时一个numpy数组或者是numpy数组的集合,`get`调用是zero-copy的,并且返回由共享对象存储内存支持的数组。否则,我们会将对象数据反序列化为Python对象。```pythony = 1obj_id = ray.put(y)assert ray.get(obj_id) == 1
你还可以设置超时时间,在阻塞时间过长时,从get中提前返回结果。
from ray.exceptions import RayTimeoutError@ray.remotedef long_running_function()time.sleep(8)obj_id = long_running_function.remote()try:ray.get(obj_id, timeout=4)except RayTimeoutError:print("`get` timed out.")
get source: ```python ray.get(object_ids, timeout=None) Get a remote object or a list of remote objects from the object store.
This method blocks until the object corresponding to the object ID is available in the local object store. If this object is not in the local object store, it will be shipped from an object store that has it (once the object has been created). If object_ids is a list, then the objects corresponding to each object in the list will be returned.
Parameters:
object_ids – Object ID of the object to get or a list of object IDs to get.
timeout (Optional[float]) – The maximum amount of time in seconds to wait before returning.
Returns:
A Python object or a list of Python objects.
Raises:
RayTimeoutError – A RayTimeoutError is raised if a timeout is set and the get takes longer than timeout to return.
Exception – An exception is raised if the task that created the object or that created one of the objects raised an exception.
启动许多任务后,您可能想知道哪些任务已完成执行。可以使用`ray.wait`完成。该函数如下:```pythonready_ids, remaining_ids = ray.wait(object_ids, num_returns=1, timeout=None)
wait source: ```python ray.wait(object_ids, num_returns=1, timeout=None)[source] Return a list of IDs that are ready and a list of IDs that are not.
Warning⚠️
The timeout argument used to be in milliseconds (up through ray==0.6.1) and now it is in seconds.
If timeout is set, the function returns either when the requested number of IDs are ready or when the timeout is reached, whichever occurs first. If it is not set, the function simply waits until that number of objects is ready and returns that exact number of object IDs.
This method returns two lists. The first list consists of object IDs that correspond to objects that are available in the object store. The second list corresponds to the rest of the object IDs (which may or may not be ready).
Ordering of the input list of object IDs is preserved. That is, if A precedes B in the input list, and both are in the ready list, then A will precede B in the ready list. This also holds true if A and B are both in the remaining list.
Parameters:
object_ids (List[ObjectID]) – List of object IDs for objects that may or may not be ready. Note that these IDs must be unique.
num_returns (int) – The number of object IDs that should be returned.
timeout (float) – The maximum amount of time in seconds to wait before returning.
Returns:
A list of object IDs that are ready and a list of the remaining object IDs.
<a name="04c37e88"></a>### Object 驱逐当对象存储空间变满时,将驱逐老的对象为新的对象腾出空间。大致按照LRU(least recently used)顺序执行。为了避免对象被驱逐,可以调用`ray.get`存储其值。Numpy数组对象在任何Python进程中映射时都无法收回。你可以配置内存限制,去控制actors对对象存储的使用。<br />使用`ray.put`创建的对象被固定在内存中,而put返回的是一个object ID引用。这种仅适用于put返回的特殊的ID,而不是常规的ID或IDs的副本。<a name="31fd3c44"></a>### 远程类(Actors)Actor将Ray API从函数(tasks)扩展到类。有`ray.remote`装饰器的Counter类的实例是一个Actor。Actor本质是一个有状态的worker。每个actor都将运行在自己的python进程中。```python@ray.remoteclass Counter(object):def __init__(self):self.value = 0def increment(self):self.value += 1return self.value
要创建一对actor,我们可以通过实例化改类:
a1 = Counter.remote()a2 = Counter.remote()
实例化一个actor,将做如下工作:
- 在集群的节点上启动一个python进程worker
- 在worker上实例化Counter对象
你也可以在actor上制定资源的需求:
@ray.remote(num_cpus=2, num_gpus=0.5)class Actor(object):pass
我们可以通过使用.remote运算符调用actor的方法来与actor进行交互。然后,我们可以在对象ID上调用ray.get来获取实际值。
obj_id = a1.increment.remote()ray.get(obj_id) == 1
在不同的actor上调用的方法可以并行执行,而在同一个actor上调用的方法则按照被调用的顺序依次执行。在相同actor的方法彼此是共享状态的,例如:
# Create ten Counter actors.counters = [Counter.remote() for _ in range(10)]# Increment each Counter once and get the results. These tasks all happen in# parallel.results = ray.get([c.increment.remote() for c in counters])print(results) # prints [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]# Increment the first Counter five times. These tasks are executed serially# and share state.results = ray.get([counters[0].increment.remote() for _ in range(5)])print(results) # prints [2, 3, 4, 5, 6]
Actors使用
Actor本质是一个有状态的worker(或者是一个service)。当一个新的actor被实例化,会创建一个新的worker,并且actor上的方法会被调度到指定的worker上,可以进行访问和更改这个worker的状态。
创建Actor
可以将标准的python类转化成Ray actor类:
@ray.remoteclass Counter(object):def __init__(self):self.value = 0def increment(self):self.value += 1return self.value
注意,下面操作等同于上面代码:
class Counter(object):def __init__(self):self.value = 0def increment(self):self.value += 1return self.valueCounter = ray.remote(Counter)
在实例化上述的actor,将发生如下动作:
- 选择集群中的某个节点,在该节点上创建一个worker进程,为了执行该acotr上的方法。
在该worker进程中创建一个Counter对象,并且会运行Counter的构造函数。
Actor方法
Actor的任何方法都可以使用
ray.method装饰器进行修饰,可以返回多个对象ID: ```python @ray.remote class Foo(object):@ray.method(num_return_vals=2) def bar(self):
return 1, 2
f = Foo.remote()
obj_id1, obj_id2 = f.bar.remote() assert ray.get(obj_id1) == 1 assert ray.get(obj_id2) == 2
<a name="db4bdfd0"></a>### Actor资源你可以通过装饰器为actor指定需要的CPUs或GPUs资源。虽然Ray内置了对CPU和GPU的支持,但也可以处理自定义的资源类型。<br />当使用GPU时,在实例化actor后Ray会自动设置环境变量`CUDA_VISIBLE_DEVICES`。actor可以通过`ray.get_gpu_ids()`访问允许使用的GPU ID列表。这是一个整数列表,例如`[], [1], [2,5,6]`。```python@ray.remote(num_cpus=2, num_gpus=1)class GPUActor(object):pass
创建GPUActor实例后,它将被放置在至少具有1个GPU的节点上,并且这个GPU资源会保留在actor的整个生命周期内(甚至该actor上没有任何执行tasks)。当actor终止时,GPU资源才会被释放。
如果你想使用自定义资源,请确保集群配置具有该自定义资源。(请查看Ray Configuring介绍)。
重点:⭐️
- 如果您在actor类的远程装饰器中指定资源需求,那么即使actor不执行任何方法,actor也会在整个生命周期中获取这些资源(如果您未指定CPU资源,则默认值为1)。执行方法时,actor将不会获得任何额外的资源。
- 如果您没有在actor类的远程装饰器中指定任何资源要求,那么默认情况下,actor在其生命周期内将不会获取任何资源,但是每次执行一个方法时,它都需要获取1个CPU资源。
@ray.remote(resources={'Resource2': 1})class GPUActor(object):pass
如果您需要实例化具有不同资源需求的同一个actor的多个副本,则可以执行以下操作:
@ray.remote(num_cpus=4)class Counter(object):def __init__(self):self.value = 0def increment(self):self.value += 1return self.valuea1 = Counter.options(num_cpus=1, resources={"Custom1": 1}).remote()a2 = Counter.options(num_cpus=2, resources={"Custom2": 1}).remote()a3 = Counter.options(num_cpus=3, resources={"Custom3": 1}).remote()
请注意,要成功创建这些actor,将需要使用足够的CPU资源和相关的自定义资源来启动Ray。
终止Actors
当初始actor句柄超出Python范围时,Actor进程将自动终止。如果我们使用actor_handle = Counter.remote()创建一个actor,当actor_handle超出范围并被破坏时,actor进程将会终止。注意,这仅适用于创建actor的原始actor手柄,不适用于通过将actor手柄传递给其他任务而创建的后续actor手柄。
如果需要,你还可以通过调用actor的方法ray.actor.exit_actor()来手工终止一个actor。这将终止actor进程并释放分配给该actor的资源。由于actor会被自动垃圾回收,因此通常不需要这种方法。
传递Actor手柄
Actor句柄可以传递给其他任务。举个简单的例子说明这一点,首先定义一个简单的acotr:
@ray.remoteclass Counter(object):def __init__(self):self.counter = 0def inc(self):self.counter += 1def get_counter(self):return self.counter
我们可以定义使用actor句柄的远程函数(或actor方法):
import time@ray.remotedef f(counter):for _ in range(1000):time.sleep(0.1)counter.inc.remote()
如果实例化一个actor,我们可以将手柄传递给各种任务:
counter = Counter.remote()# Start some tasks that use the actor.[f.remote(counter) for _ in range(3)]# Print the counter value.for _ in range(10):time.sleep(1)print(ray.get(counter.get_counter.remote()))
GPU支持
GPU对于许多机器学习应用程序至关重要。Ray可以在远程函数和actor通过ray.remote装饰器指定其GPU的要求。
启动Ray with GPUs
Ray会自动检测机器上可用的GPU数量。如果需要,也可以通过指定ray.init(num_gpus=N) 或 ray start --num-gpus=N来覆盖配置。
注意:你是可以传入大于计算机上真实的GPU数量的num_gpus的值。在这种情况下,Ray会像机器上具有你指定的GPU数量一样,来调度需要GPU的任务。仅当这些任务尝试实际使用不存在的GPU时,才会发生故障。
远程函数with GPUs
如果远程函数执行需要GPU,请在装饰器中指定所需GPU的数量:
import os@ray.remote(num_gpus=1)def use_gpu():print("ray.get_gpu_ids(): {}".format(ray.get_gpu_ids()))print("CUDA_VISIBLE_DEVICES: {}".format(os.environ["CUDA_VISIBLE_DEVICES"]))
在远程函数内部,调用ray.get_gpu_ids()将返回一个整数列表,表示允许远程函数使用哪些GPU ID。不过,通常不需要调用ray.get_gpu_ids(),因为Ray会自动设置在CUDA_VISIBLE_DEVICES环境变量中。
注意:上面定义的use_gpu函数实际上并未使用任何GPU。Ray会将其调度到具有至少一个GPU的机器上,并在执行时为其保留一个GPU,但是这取决于实际使用GPU的函数。这通常通过TensorFlow之类的外部库完成。这是一个实际使用GPU的示例。请注意,要使此示例正常运行,您将需要安装TensorFlow的GPU版本:
import tensorflow as tf@ray.remote(num_gpus=1)def use_gpu():# Create a TensorFlow session. TensorFlow will restrict itself to use the# GPUs specified by the CUDA_VISIBLE_DEVICES environment variable.tf.Session()
注意:实现use_gpu的人可以忽略ray.get_gpu_ids并使用计算机上所有的GPU。这可能导致太多workers同时使用同一个GPU,但Ray不会阻止这样的情况发生。但是,Ray会自动设置CUDA_VISIBLE_DEVICES环境变量,这将限制大多数深度学习框架使用的GPU。
小数GPUs
如果要两个任务共享同一个GPU,则每个任务都可以请求GPU的一半(或其他分数)。
import rayimport timeray.init(num_cpus=4, num_gpus=1)@ray.remote(num_gpus=0.25)def f():time.sleep(1)# The four tasks created here can execute concurrently.ray.get([f.remote() for _ in range(4)])
开发人员需要确保各个任务的使用量不超过其GPU内存的份额。 TensorFlow可以配置为限制其内存使用量。
GPUs上使用Actor
定义使用GPU的actor时,请在ray.remote装饰器中指明一个actor实例所需的GPU数量。
@ray.remote(num_gpus=1)class GPUActor(object):def __init__(self):return "This actor is allowed to use GPUs {}.".format(ray.get_gpu_ids())
创建Actor后,将在该Actor的整个生命周期内保留GPU。如果没有足够的GPU资源,则不会创建actor。
以下是如何通过TensorFlow在actor中使用GPU的示例:
@ray.remote(num_gpus=1)class GPUActor(object):def __init__(self):# The call to tf.Session() will restrict TensorFlow to use the GPUs# specified in the CUDA_VISIBLE_DEVICES environment variable.self.sess = tf.Session()
Workers不释放GPU资源
注意:目前,当worker执行使用GPU的任务时(例如通过TensorFlow),该任务可能会在GPU上分配内存,并且在任务完成执行后可能不会释放内存。下次任务尝试使用同一GPU时,这可能会导致问题。您可以通过在remote装饰器中设置max_calls = 1来解决此问题,以便worker在执行任务后自动退出(从而释放GPU资源)。
import tensorflow as tf@ray.remote(num_gpus=1, max_calls=1)def leak_gpus():# This task will allocate memory on the GPU and then never release it, so# we include the max_calls argument to kill the worker and release the# resources.sess = tf.Session()
序列化
由于Ray进程不共享内存空间,因此需要对worker进程和节点之间传输的数据进行序列化和反序列化。Ray使用Plasma对象存储在不同的进程和不同的节点之间高效地传输对象。对象存储中的Numpy数组在同一节点上的worker程序之间共享(零复制反序列化)。
Plasma对象存储
Plasma是一种内存对象存储,作为Apache Arrow的一部分进行开发。Ray使用Plasma对象存储在不同的进程和不同的节点之间高效地传输对象。Plasma对象存储中的所有对象都是不可变的,并保存在共享内存中。这样,同一节点上的许多workers就可以有效地访问它们。
每个节点都有自己的对象存储。将数据放入对象存储时,不会自动将其广播到其他节点。数据一直保持在本地写入,直到另一个节点上的另一个task或actor请求为止。
序列化对象在Ray进程之间传输经历的三个阶段:
- 使用pyarrow进行序列化:以下是Ray可以使用pyarrow进行序列化的一组Python对象:
- 基本类型: ints, floats, longs, bools, strings, unicode, and numpy arrays.
- 任何list, dictionary, tuple其元素可以被Ray序列化
__dict__序列化:如果无法直接使用PyArrow,Ray将递归提取对象的__dict__并使用pyarrow序列化该对象。在所有情况下,此行为都不正确。- Cloudpickle:作为序列化的最终尝试,Ray使用
cloudpickle。这可能很慢。Numpy Arrays
Ray通过使用Apache Arrow数据格式来优化numpy数组。numpy数组存储为只读对象,并且同一节点上的所有Ray worker均可读取对象存储中的numpy数组而无需进行复制(零复制读取)。worker进程中的每个numpy数组对象都拥有一个指向共享内存中相关数组的指针。对只读对象的任何写操作都要求用户首先将其复制到本地处理内存中。
Tip: 通常你可以仅使用native类型(例如 numpy arrays or lists/dicts of numpy arrays and other primitive types)来避免序列化问题,或者使用Actors来持有无法序列化的对象。序列话说明和限制
根据Python的语义,当前Ray错误地处理了某些模式。例如,包含两个相同list副本的列表将被序列化,就好像两个list是不同的一样。 ```python l1 = [0] l2 = [l1, l1] l3 = ray.get(ray.put(l2))
assert l2[0] is l2[1] assert not l3[0] is l3[1]
由于与上述示例相似的原因,目前还不能处理递归包含自身的对象(这在类似图形的数据结构中很常见)。```pythonl = []l.append(l)# Try to put this list that recursively contains itself in the object store.ray.put(l)
这将引发异常,显示如下消息:
This object exceeds the maximum recursion depth. It may contain itself recursively.
尽可能使用numpy数组或numpy数组的Python集合来获得最佳性能。
最后一招:自定义序列化
如果上述选项都不起作用,则可以尝试注册自定义序列化。
ray.register_custom_serializer(cls, serializer=None, deserializer=None, use_pickle=False, use_dict=False, local=None, job_id=None, class_id=None)[source]Registers custom functions for efficient object serialization.The serializer and deserializer are used when transferring objects of cls across processes and nodes. This can be significantly faster than the Ray default fallbacks. Wraps register_custom_serializer underneath.use_pickle tells Ray to automatically use cloudpickle for serialization, and use_dict automatically uses cls.__dict__.When calling this function, you can only provide one of the following:1. serializer and deserializer2. use_pickle3. use_dictParameters:cls (type) – The class that ray should use this custom serializer for.serializer – The custom serializer that takes in a cls instance and outputs a serialized representation. use_pickle and use_dict must be False if provided.deserializer – The custom deserializer that takes in a serialized representation of the cls and outputs a cls instance. use_pickle and use_dict must be False if provided.use_pickle (bool) – If true, objects of this class will be serialized using pickle. Must be False if use_dict is true.use_dict (bool) – If true, objects of this class be serialized turning their __dict__ fields into a dictionary. Must be False if use_pickle is true.local – Deprecated.job_id – Deprecated.class_id (str) – Unique ID of the class. Autogenerated if None.
实例:
import rayray.init()class Foo(object):def __init__(self, value):self.value = valuedef custom_serializer(obj):return obj.valuedef custom_deserializer(value):object = Foo()object.value = valuereturn objectray.register_custom_serializer(Foo, serializer=custom_serializer, deserializer=custom_deserializer)object_id = ray.put(Foo(100))assert ray.get(object_id).value == 100
内存管理
本节会描述内存管理在Ray中的工作方式,以及如何设置内存配额以确保内存密集型应用程序可预测且可靠地运行。
Ray应用程序使用内存的几种方式:
Ray系统内存:在Ray内部使用的内存
- Redis:用于存储任务血缘和对象元数据的内存。当内存满了,血缘数据将根据LRU进行驱逐,这使得对应的对象会不符合失败重建的条件。
- Raylet: 每个节点上运行的C ++ raylet进程使用的内存。这是无法控制的,但是通常很小。
应用程序内存:你的应用程序使用的内存
- Worker heap: 应用程序使用的内存(例如:python代码或者TensorFlow)最好用应用程序的常驻大小(RSS)减去诸如top之类的命令共享内存使用率(SHR)来衡量。需要减去SHR的原因是操作系统将对象存储共享内存报告为每个worker共享的。不减去SHR将导致重复计算内存使用量。
- Object store memory:应用程序通过
ray.put在对象存储中创建的对象以及从远程函数返回值时使用的内存。当存储空间满时,根据LRU驱逐对象,优先考虑那些长时间不在dirver或任何worker的对象。在每个节点上都有一个运行的对象存储服务。 - Object store shared memory: 应用程序通过
ray.get读取对象时使用的内存。注意,如果节点上对象已经存在,则不会引起额外分配。这使得大型对象可以在许多actors和task之间有效地共享。
默认情况下,Ray会将Redis使用的内存限制为min(30% of node memory, 10GiB),而对象存储为min(10% of node memory, 20GiB),节点上的剩余内存的一半留给worker heap使用。您还可以通过在Ray初始化上进行手工设置:redis_max_memory=<bytes> 和object_store_memory=<bytes>。
请务必注意,这些默认的Redis和对象存储限制不会解决以下问题:
- Actor或task堆的使用量超过了节点上的剩余可用内存。
- 某些actor或task大量使用对象存储,导致其他task所需的对象过早地被驱逐掉。
为避免这些潜在的不稳定因素,您可以设置内存配额为单个actor和task保留内存。
堆内存配额
当Ray启动时,它将查询未为Redis和对象存储保留或未被其他应用程序使用的节点/容器上的可用内存。这被认为是actors和tasks可以从中请求的“可用内存”。您还可以在Ray初始化上设置memory = <bytes>,以明确告知Ray可用的内存量。
Note:
设置节点的可用内存不会对任务的内存使用施加任何限制。要设置每个任务的内存限制,请参考:
要告诉Ray调度task或actor需要一定数量的可用内存才能运行,请设置memory参数。然后,Ray调度程序将在调度过程中保留指定数量的可用内存,类似于它处理CPU和GPU资源的方式:
# reserve 500MiB of available memory to place this task@ray.remote(memory=500 * 1024 * 1024)def some_function(x):pass# reserve 2.5GiB of available memory to place this actor@ray.remote(memory=2500 * 1024 * 1024)class SomeActor(object):def __init__(self, a, b):pass
上面示例中,内存配额是由装饰器静态指定的,但你也可以在运行时使用.options()动态设置,例如:
# override the memory quota to 100MiB when submitting the tasksome_function.options(memory=100 * 1024 * 1024).remote(x=1)# override the memory quota to 1GiB when creating the actorSomeActor.options(memory=1000 * 1024 * 1024).remote(a=1, b=2)
如果actor超出其内存配额,对其的调用将引发RayOutOfMemoryError并可能被杀死。当前仅在actor的最大努力基础上强制执行内存配额(但在所有情况下的调度过程中都会考虑配额)。
对象存储内存配额
使用@ ray.remote(object_store_memory = <bytes>)限制actor可用于ray.put和方法调用返回的内存量。这将为actor在给定大小的对象存储中提供自己的LRU队列,这样既可以保护器对象免受其他actor的驱逐,又可以防止其使用超过指定配额的对象。当某些actor比其他以高得多的速率生成对象时,此配额可防止对象收到不正当的驱逐。
Ray在调度过程中考虑了资源,但需要注意的是一个节点将始终保留其对象存储的30%供全局共享使用。
对于driver可以使用driver_object_store_memory设置其对象存储的内存配额。task不支持设置对象存储配额。
对象存储共享内存
对象存储内存还用于将ray.get调用返回的对象映射到共享内存中。虽然以这种方式映射对象(即,有一个对该对象的python引用),但该对象是固定的,无法从对象存储中逐出。但是,Ray不为这种共享内存使用提供配额管理。
您可以设置内存配额,以确保您的应用程序可以在任何Ray群集配置上正常运行。如果不确定,则可以从如下所示的保守默认配置开始,看看是否达到任何限制:
@ray.remote(memory=2000 * 1024 * 1024,object_store_memory=200 * 1024 * 1024)
调试和分析
高级用法
动态远程参数
您可以使用.options在执行期间动态调整资源需求或ray.remote的返回值。
例如,我们实例化具有不同资源需求的同一个actor的许多副本。请注意,要成功创建这些actor需要使用足够的CPU资源和相关的自定义资源来启动Ray:
@ray.remote(num_cpus=4)class Counter(object):def __init__(self):self.value = 0def increment(self):self.value += 1return self.valuea1 = Counter.options(num_cpus=1, resources={"Custom1": 1}).remote()a2 = Counter.options(num_cpus=2, resources={"Custom2": 1}).remote()a3 = Counter.options(num_cpus=3, resources={"Custom3": 1}).remote()
您可以为task指定不同的资源要求(但不能为actor方法指定):
@ray.remotedef g():return ray.get_gpu_ids()object_gpu_ids = g.remote()assert ray.get(object_gpu_ids) == [0]dynamic_object_gpu_ids = g.options(num_cpus=1, num_gpus=1).remote()assert ray.get(dynamic_object_gpu_ids) == [0]
更改tasks(以及actor方法)的返回值数量:
@ray.remotedef f(n):return list(range(n))id1, id2 = f.options(num_return_vals=2).remote(2)assert ray.get(id1) == 0assert ray.get(id2) == 1
动态自定义资源
通过使用自定义资源,Ray可以task和actor的位置进行明确的控制。此外,用户可以使用ray.experimental.set_resource以编程方式动态调整自定义资源。这使Ray应用程序实际上可以实现任何调度策略,包括任务亲缘关系,数据局部性,反亲和力,负载平衡,组调度和基于优先级的调度:
resource_name = "test_resource"resource_capacity = 1.0@ray.remotedef set_resource(resource_name, resource_capacity):ray.experimental.set_resource(resource_name, resource_capacity)ray.get(set_resource.remote(resource_name, resource_capacity))available_resources = ray.available_resources()cluster_resources = ray.cluster_resources()assert available_resources[resource_name] == resource_capacityassert cluster_resources[resource_name] == resource_capacity
```python ray.experimental.set_resource(resource_name, capacity, client_id=None) Set a resource to a specified capacity.
This creates, updates or deletes a custom resource for a target clientId. If the resource already exists, it’s capacity is updated to the new value. If the capacity is set to 0, the resource is deleted. If ClientID is not specified or set to None, the resource is created on the local client where the actor is running.
Parameters:
resource_name (str) – Name of the resource to be created
capacity (int) – Capacity of the new resource. Resource is deleted if capacity is 0.
client_id (str) – The ClientId of the node where the resource is to be set.
Returns:
None
Raises:
ValueError – This exception is raised when a non-negative capacity is specified.
<a name="30fb50c8"></a>### 嵌套的远程函数远程函数可以调用其他远程函数,从而导致嵌套任务。例如:```python@ray.remotedef f():return 1@ray.remotedef g():# Call f 4 times and return the resulting object IDs.return [f.remote() for _ in range(4)]@ray.remotedef h():# Call f 4 times, block until those 4 tasks finish,# retrieve the results, and return the values.return ray.get([f.remote() for _ in range(4)])
然后调用g和h会获得:
>>> ray.get(g.remote())[ObjectID(b1457ba0911ae84989aae86f89409e953dd9a80e),ObjectID(7c14a1d13a56d8dc01e800761a66f09201104275),ObjectID(99763728ffc1a2c0766a2000ebabded52514e9a6),ObjectID(9c2f372e1933b04b2936bb6f58161285829b9914)]>>> ray.get(h.remote())[1, 1, 1, 1]
有个限制是f的定义必须优先于g和h的定义,因为一旦定义了g就会pickled并发送到workers,因此,如果尚未定义f,整个定义将不完整。
循环依赖
@ray.remote(num_cpus=1, num_gpus=1)def g():return ray.get(f.remote())
当执行g任务时,当它在对ray.get的调用中被阻塞时,它将释放其CPU资源。当ray.get返回时,它将重新获取CPU资源。它会在任务的整个生命周期中保留其GPU资源,因为任务很可能会继续使用GPU内存。
Ray中Cython代码
要在Ray中使用Cython代码,请在$RAY_HOME/examples/cython目录中运行如下命令:
pip install scipy # For BLAS examplepip install -e .python cython_main.py --help
您可以从Python脚本或解释器导入cython_examples模块。
注意:
您必须在任何
* .pyx文件的顶部包含以下两行:```python!python
cython: embedsignature=True, binding=True
```
您无法在
* .pyx文件中修饰Cython函数(有多种解决方法,但是会在Cython和Python之间创建弱抽象,通常很难对其进行支持)。相反,请在Python代码中使用以下代码:python some_cython_func = ray.remote(some_cython_module.some_cython_func)您不能将内存缓冲区传输到远程函数(请参见
example8,该操作当前会失败);您的远程函数必须返回一个值。- 有关如何调用,定义和构建Cython代码的示例,请查看
cython_main.py,cython_simple.pyx和setup.py。 - 部分限制来自Cython自身不支持的python功能。
- 我们目前不支持将Cython代码编译和分发到ray群集。换句话说,Cython开发人员需要将任何Cython代码编译并分发到他们的集群(这与scipy这样的Python包类似)。
- 对于大多数简单的用例,开发人员不必担心是python2或3,但是注意查看Cython编译器指令的
language_level检查集群状态
在Ray之上编写的应用程序通常希望获得有关集群的某些信息或诊断信息。常见问题包括:
- 我的自动伸缩群集中有多少个节点?
- 我的集群中当前有哪些可用资源,包括已用资源和总计资源是多少?
- 我的集群中当前有哪些对象?
节点信息
要获取有关集群中当前节点的信息,可以使用ray.nodes():
```python ray.nodes() Get a list of the nodes in the cluster.
Returns: Information about the Ray clients in the cluster.
>```pythonimport rayray.init()print(ray.nodes())"""[{'ClientID': 'a9e430719685f3862ed7ba411259d4138f8afb1e','IsInsertion': True,'NodeManagerAddress': '192.168.19.108','NodeManagerPort': 37428,'ObjectManagerPort': 43415,'ObjectStoreSocketName': '/tmp/ray/session_2019-07-28_17-03-53_955034_24883/sockets/plasma_store','RayletSocketName': '/tmp/ray/session_2019-07-28_17-03-53_955034_24883/sockets/raylet','Resources': {'CPU': 4.0},'alive': True}]"""
以上信息包括:
- ClientID:raylet的唯一标识符。
- alive:该节点是否仍然存活。
- NodeManagerAddress:raylet所在的节点的PrivateIP。
- Resources:节点上的总资源容量。
资源信息
要获取有关群集当前总资源容量的信息,可以使用ray.cluster_resources()。 ```python ray.cluster_resources() Get the current total cluster resources.
Note that this information can grow stale as nodes are added to or removed from the cluster.
Returns:
A dictionary mapping resource name to the total quantity of that
resource in the cluster.
要获取有关集群当前可用资源容量的信息,可以使用`ray.available_resources()`。```pythonray.available_resources()Get the current available cluster resources.This is different from cluster_resources in that this will return idle (available) resources rather than total resources.Note that this information can grow stale as tasks start and finish.Returns:A dictionary mapping resource name to the total quantity of thatresource in the cluster.
独立的Actors
当原始的actor句柄超出范围或最初创建actor的driver程序退出时,ray默认情况下会清理actor。如果要确保actor保持活动状态,可以在driver程序退出后使用_remote(name="some_name", detached=True)使actor保持活动状态。Actor具有全局唯一的名称,并且可以在不同的driver程序之间进行访问。
例如,你可以按以下方式实例化并注册一个持久性的actor:
counter = Counter.options(name="CounterActor", detached=True).remote()
即使在上述脚本中运行的driver程序退出后,CounterActor也将保持活动状态。因此,可以在其他driver程序中运行以下脚本:
counter = ray.experimental.get_actor("CounterActor")print(ray.get(counter.get_counter.remote()))
请注意,只允许创建一个命名的actor,该actor将在driver程序退出后被清除:
Counter.options(name="CounterActor").remote()
但是,不允许创建没有名称的独立的actor,因为将无法检索actor句柄,资源会被泄漏。
# Can't do this!Counter.options(detached=True).remote()
最佳实践:Ray with Tensorflow
最佳实践:Ray with PyTorch
Ray配置
本节讨论从python API和命令行配置Ray的各种方法。查看ray.init文档可以获得配置的完整概述。
对于多节点设置,必须先在命令行中运行ray start,然后才能在Python中运行ray.init。在单机上,你可以直接运行ray.init而不需要执行ray start。
集群资源
Ray默认情况下会检测可用资源。
# This automatically detects available resources in the single machine.ray.init()
如果未运行群集模式,则可以通过ray.init指定群集资源替代,如下所示:
# If not connecting to an existing cluster, you can specify resources overrides:ray.init(num_cpus=8, num_gpus=1)# Specifying custom resourcesray.init(num_gpus=1, resources={'Resource1': 4, 'Resource2': 16})
从命令行启动Ray时,将--num-cpus和--num-cpus标志传递到ray start中。您还可以指定自定义资源。
# To start a head node.$ ray start --head --num-cpus=<NUM_CPUS> --num-gpus=<NUM_GPUS># To start a non-head node.$ ray start --address=<address> --num-cpus=<NUM_CPUS> --num-gpus=<NUM_GPUS># Specifying custom resourcesray start [--head] --num-cpus=<NUM_CPUS> --resources='{"Resource1": 4, "Resource2": 16}'
使用命令行连接到Ray集群,如下:
# Connect to ray. Notice if connected to existing cluster, you don't specify resources.ray.init(address=<address>)
日志和调试
每个Ray会话将有唯一的名称。默认情况下,名称为session_{timestamp}_{pid}。时间戳格式为%Y-%m-%d_%H-%M-%S_%f。pid属于启动进程(调用ray,init()的进程或由ray start在shell中执行的Ray进程)。
对于每个会话,Ray会将其所有临时文件放在会话目录下。会话目录是根临时路径(默认为/tmp/ray)下的子目录,所以默认会话目录为/tmp/ray/{ray_session_name}。
通过以下方式之一可以更改根临时目录:
ray start时配置--temp-dir={your temp path}参数- 调用
ray.init()时指定temp_dir
您也可以使用default_worker.py --temp-dir={your temp path}指定根临时目录来启动新worker进程。
Layout of logs:
/tmp└── ray└── session_{datetime}_{pid}├── logs # for logging│ ├── log_monitor.err│ ├── log_monitor.out│ ├── monitor.err│ ├── monitor.out│ ├── plasma_store.err # outputs of the plasma store│ ├── plasma_store.out│ ├── raylet.err # outputs of the raylet process│ ├── raylet.out│ ├── redis-shard_0.err # outputs of redis shards│ ├── redis-shard_0.out│ ├── redis.err # redis│ ├── redis.out│ ├── webui.err # ipython notebook web ui│ ├── webui.out│ ├── worker-{worker_id}.err # redirected output of workers│ ├── worker-{worker_id}.out│ └── {other workers}└── sockets # for sockets├── plasma_store└── raylet # this could be deleted by Ray's shutdown cleanup.
Redis端口认证
Ray实例应在没有面向公共端口的安全网络上运行。Ray实例最常见的威胁是对Redis的未授权访问,可以利用该漏洞获得Shell访问权限并运行任意代码。最好的解决方法是在安全,可信任的网络上运行Ray实例。
在安全的网络上运行Ray并不总是可行的。为了防止通过未经授权的Redis访问进行利用,Ray提供了使用密码保护Redis端口的选项。虽然这不能替代在防火墙后运行Ray的功能,但此功能对于无法配置防火墙暴露于Internet的Ray实例很有用。由于Redis处理查询的速度非常快,因此选择的密码应该很长。
仅在raylet代码路径上支持Redis身份验证。要通过Python API添加身份验证,请使用以下命令启动Ray:
ray.init(redis_password="password")
通过CLI添加身份验证或使用密码保护的Redis端口连接到现有的Ray实例,请执行以下操作:
ray start [--head] --redis-password="password"
尽管Redis端口身份验证可以抵御外部攻击者,但Ray不会对节点之间的流量进行加密,因此,对于不受信任的网络上的群集,中间被人攻击是可能的。
对象存储与大页面使用
Ray部署
自动集群设置
Ray带有内置的自动伸缩器,使部署Ray群集变得简单,只需从本地计算机执行ray up即可启动或更新到云中或本地群集上。Ray群集运行后,您可以手动将SSH到群集中,或使用提供的命令如(ray Attach,ray rsync-up和ray-exec)访问它并运行Ray程序。
本节提供了有关配置自动伸缩器,在AWS/GCP或现有的K8s集群或专有机器上启动Ray集群的说明。
AWS
首先,按照boto文档中的说明安装boto(pip install boto3),并在~/.aws/credentials配置你的AWS凭证。
将boto配置为管理您的AWS账户上的资源后,就可以准备运行自动伸缩器了。提供的 ray/python/ray/autoscaler/aws/example-full.yaml 群集配置文件将创建一个小型群集,该群集具有m5.large头节点(按需配置),可自动缩放最多两个m5.large spot workers。
通过从本地计算机运行以下命令来测试其是否有效:
# Create or update the cluster. When the command finishes, it will print# out the command that can be used to SSH into the cluster head node.$ ray up ray/python/ray/autoscaler/aws/example-full.yaml# Get a remote screen on the head node.$ ray attach ray/python/ray/autoscaler/aws/example-full.yaml$ source activate tensorflow_p36$ # Try running a Ray program with 'ray.init(address="auto")'.# Tear down the cluster.$ ray down ray/python/ray/autoscaler/aws/example-full.yaml
GCP
首先,安装Google API客户端(pip install google-api-python-client),设置您的GCP凭据,然后创建一个新的GCP项目。
一旦将API客户端配置为管理GCP帐户上的资源,就可以准备运行自动伸缩器。提供的ray/python/ray/autoscaler/gcp/example-full.yaml群集配置文件将创建一个小型群集,该群集具有n1-standard-2头节点(按需配置),可自动缩放至两个n1-standard-2 preemptible workers。
通过从本地计算机运行以下命令来测试其是否有效:
# Create or update the cluster. When the command finishes, it will print# out the command that can be used to SSH into the cluster head node.$ ray up ray/python/ray/autoscaler/gcp/example-full.yaml# Get a remote screen on the head node.$ ray attach ray/python/ray/autoscaler/gcp/example-full.yaml$ source activate tensorflow_p36$ # Try running a Ray program with 'ray.init(address="auto")'.# Tear down the cluster.$ ray down ray/python/ray/autoscaler/gcp/example-full.yaml
Kubernetes
自动伸缩器还可用于在现有Kubernetes集群上启动Ray集群。首先,安装Kubernetes API客户端(pip install kubernetes),然后确保正确设置了Kubernetes凭据并能访问集群(如果像kubectl get pods这样的命令成功执行,则应该可以使用)。
一旦在本地配置了kubectl来访问远程集群,就可以准备运行自动伸缩器。所提供的 ray/python/ray/autoscaler/kubernetes/example-full.yaml 群集配置文件将为头节点创建一个包含一个Pod的小型群集,可自动缩放最多两个工作节点Pod,所有Pod都需要1个CPU和0.5GiB内存。
通过从本地计算机运行以下命令来测试其是否有效:
# Create or update the cluster. When the command finishes, it will print# out the command that can be used to get a remote shell into the head node.$ ray up ray/python/ray/autoscaler/kubernetes/example-full.yaml# List the pods running in the cluster. You shoud only see one head node# until you start running an application, at which point worker nodes# should be started. Don't forget to include the Ray namespace in your# 'kubectl' commands ('ray' by default).$ kubectl -n ray get pods# Get a remote screen on the head node.$ ray attach ray/python/ray/autoscaler/kubernetes/example-full.yaml$ # Try running a Ray program with 'ray.init(address="auto")'.# Tear down the cluster$ ray down ray/python/ray/autoscaler/kubernetes/example-full.yaml
私有集群
自动伸缩器还可用于在主机的专用群集上运行Ray群集,该群集指定为要连接的计算机IP地址的列表。您可以通过填写提供的ray/python/ray/autoscaler/local/example-full.yaml中的字段来开始使用。确保指定正确的head_ip,worker_ips列表和ssh_user字段。
通过从本地计算机运行以下命令来测试其是否有效:
# Create or update the cluster. When the command finishes, it will print# out the command that can be used to get a remote shell into the head node.$ ray up ray/python/ray/autoscaler/local/example-full.yaml# Get a remote screen on the head node.$ ray attach ray/python/ray/autoscaler/local/example-full.yaml$ # Try running a Ray program with 'ray.init(address="auto")'.# Tear down the cluster$ ray down ray/python/ray/autoscaler/local/example-full.yaml
外部节点提供者
Ray还支持外部节点提供程序(请查看node_provider.py 实现)。您可以使用yaml配置指定外部节点提供程序:
provider:type: externalmodule: mypackage.myclass
该模块的格式必须为 package.provider_class 或 package.sub_package.provider_class。
其他云提供商
要在其他Cloud provider或集群管理系统上使用Ray自动伸缩,您可以实现NodeProvider接口并将其注册在node_provider.py中。欢迎捐款!
快速开始
启动和更新集群
使用现有群集运行ray up时,该命令将检查本地配置是否与群集的应用配置不同。这包括对在配置file_mounts部分中指定的同步文件的任何更改。如果有改动,新文件和配置将被上载到集群。然后,Ray服务将重新启动。
如果群集处于不良状态,您也可以运行ray up来重新启动群集(即使没有配置更改,这也会重新启动所有Ray服务)。
如果您不希望更新重新启动服务(例如,因为某些更改不需要重新启动),请将--no-restart传递给更新调用。
# Replace '<your_backend>' with one of: 'aws', 'gcp', 'kubernetes', or 'local'.$ BACKEND=<your_backend># Create or update the cluster.$ ray up ray/python/ray/autoscaler/$BACKEND/example-full.yaml# Reconfigure autoscaling behavior without interrupting running jobs.$ ray up ray/python/ray/autoscaler/$BACKEND/example-full.yaml \--max-workers=N --no-restart# Tear down the cluster.$ ray down ray/python/ray/autoscaler/$BACKEND/example-full.yaml
在新集群和现有集群上运行命令
您可以使用ray exec方便地在群集上运行命令。请注意,您运行的脚本应通过ray.init(address="auto")连接到Ray。
# Run a command on the cluster$ ray exec cluster.yaml 'echo "hello world"'# Run a command on the cluster, starting it if needed$ ray exec cluster.yaml 'echo "hello world"' --start# Run a command on the cluster, stopping the cluster after it finishes$ ray exec cluster.yaml 'echo "hello world"' --stop# Run a command on a new cluster called 'experiment-1', stopping it after$ ray exec cluster.yaml 'echo "hello world"' \--start --stop --cluster-name experiment-1# Run a command in a detached tmux session$ ray exec cluster.yaml 'echo "hello world"' --tmux# Run a command in a screen (experimental)$ ray exec cluster.yaml 'echo "hello world"' --screen
您还可以使用ray submit在集群上执行Python脚本。这会将指定的文件重新同步到群集上,并使用给定的参数执行它。
# Run a Python script in a detached tmux session$ ray submit cluster.yaml --tmux --start --stop tune_experiment.py
附加到运行的集群
您可以使用ray attach附加到群集上的交互式屏幕会话。
# Open a screen on the cluster$ ray attach cluster.yaml# Open a screen on a new cluster called 'session-1'$ ray attach cluster.yaml --start --cluster-name=session-1# Attach to tmux session on cluster (creates a new one if none available)$ ray attach cluster.yaml --tmux
端口转发应用
如果要从Web浏览器访问群集上运行的应用程序(例如Jupyter笔记本电脑),则可以对ray exec使用--port-forward选项。打开与远程端口相同的本地端口。
$ ray exec cluster.yaml --port-forward=8899 'source ~/anaconda3/bin/activate tensorflow_p36 && jupyter notebook --port=8899'
手动同步文件
要将文件下载或上传到群集头节点,请使用ray rsync_down或ray rsync_up:
$ ray rsync_down cluster.yaml '/path/on/cluster' '/local/path'$ ray rsync_up cluster.yaml '/local/path' '/path/on/cluster'
安全性
在云提供商上,默认情况下,节点将被启动到其自己的安全组中,并且只允许同一组中的节点之间的流量互通。也将创建一个新的SSH密钥,并将其保存到本地计算机上以访问群集。
自动伸缩
Ray群集带有基于负载的自动伸缩器。当群集资源使用率超过配置的阈值(默认为80%)时,将启动新节点达到指定的max_workers限制。当节点空闲超过超时时,它们将被删除,直到min_workers限制。头节点永远不会删除。
默认的空闲超时为5分钟。这是为了防止过多的节点抖动可能影响性能并增加成本(在AWS / GCP中,每个实例的最低计费时间为1分钟,此后按秒计费)。
监控集群状态
您可以通过在/tmp/ray/session_*/logs/monitor*中自动扩展日志来监视集群使用情况和自动扩展状态。
Ray自动伸缩器以实例标签的形式报告每个节点的状态。在您的云提供商控制台中,您可以单击一个节点,转到“标签”窗口,然后将ray-node-status标签添加为一列。这使您可以一目了然地查看每个节点的状态:
自定义集群设置
建议您复制示例YAML文件并根据需要进行修改。这可能包括添加其他安装命令以安装库或同步本地数据文件。
自定义节点后,创建一个新的机器镜像(或docker容器)并在配置文件中使用它也是一个好主意。这减少了工作人员的设置时间,提高了自动伸缩的效率。
理想情况下,您使用的安装命令应该是幂等的,即可以多次运行。这使Ray在创建节点后可以更新它们。通常,您可以对命令进行幂等的修改,例如git clone foo可以重写为test -e foo || git clone foo,它检查存储库是否已被克隆。
大多数示例YAML文件是可选的。这是一个参考性的最小YAML文件reference minimal YAML file,您可以在此YAML文件中找到可选字段的默认值optional fields in this YAML file。
同步git分支
一个常见的用例是将特定的本地git分支同步到群集的所有worker上。但是,如果仅在设置命令中放入git checkout <branch>,自动伸缩器将不知道何时重新运行命令以获取更新。为此,有一个不错的解决方法,即将git SHA包含在输入中(如果更新了分支,则文件的哈希值将更改):
file_mounts: {"/tmp/current_branch_sha": "/path/to/local/repo/.git/refs/heads/<YOUR_BRANCH_NAME>",}setup_commands:- test -e <REPO_NAME> || git clone https://github.com/<REPO_ORG>/<REPO_NAME>.git- cd <REPO_NAME> && git fetch && git checkout `cat /tmp/current_branch_sha`
这告诉Ray去同步当前git分支SHA从个人计算机到集群的一个临时文件。然后,安装程序命令读取该文件,以找出节点上需要检出的SHA。请注意,每个命令都在自己的会话中运行。然后,用于更新集群的最终工作流程如下:
- 对git分支进行本地更改
- 使用
git commit和git push提交更改 - 使用
ray up更新Ray群集上的文件使用Amazon EFS
通用集群配置
配置文件example-full.yaml足够开始使用Ray。但是对于更多计算密集型工作负载,你需要更改实例类型,如通过编辑yaml使用GPU或更大的计算实例。以下是一些常见的配置:
GPU单节点:在单个大型GPU实例上使用Ray:max_workers: 0head_node:InstanceType: p2.8xlarge
Docker:指定docker镜像。这将在docker容器中的所有节点上执行所有命令,并打开所有必需的端口以支持Ray集群。如果未安装Docker,它将自动安装Docker。当前不支持GPU:
docker:image: tensorflow/tensorflow:1.5.0-py3container_name: ray_docker
GPU和CPU混合节点:对于需要比CPU资源更多地占用CPU的RL应用程序,可以将其他CPU workers与GPU头节点一起使用:
max_workers: 10head_node:InstanceType: p2.8xlargeworker_nodes:InstanceType: m4.16xlarge
自动伸缩CPU集群**:使用较小的头节点,并根据需要让Ray自动缩放workers。对于具有突发性工作负载的群集,这可能是一种经济高效的配置。您也可以要求spot workers节省更多成本:
min_workers: 0max_workers: 10head_node:InstanceType: m4.largeworker_nodes:InstanceMarketOptions:MarketType: spotInstanceType: m4.16xlarge
自动伸缩GPU集群:与自动缩放CPU群集类似,使用GPU工作节点代替:
min_workers: 0 # NOTE: older Ray versions may need 1+ GPU workers (#2106)max_workers: 10head_node:InstanceType: m4.largeworker_nodes:InstanceMarketOptions:MarketType: spotInstanceType: p2.xlarge
手动集群设置
本节说明适用于小型集群。对于较大集群,请考虑使用pssh包sudo apt-get install pssh执行或专用集群的设置命令。
在集群上部署Ray
本部分假定您正在运行一个集群,并且该集群中的节点可以相互通信。还假定在每台计算机上都安装了Ray。要安装Ray,请看安装说明。
在每台机器上启动Ray
在头节点上(只需选择一些节点作为头节点),运行以下命令。(如果省略--redis-port参数,Ray将随机选择一个端口)
ray start --head --redis-port=6379
该命令将打印出已启动的Redis服务器的地址(以及其他一些地址信息)。
然后在所有其他节点上,运行以下命令。确保将<address>替换为头节点上命令打印的值(类似于123.45.67.89:6379)。
ray start --address=<address>
如果希望指定一台计算机具有10个CPU和1个GPU,则可以使用--num-cpus = 10和--num-gpus = 1标志来实现。更多信息请看配置章节。
现在,我们已经在每个节点上启动了所有Ray进程。这包括:
- 每台计算机上都有一些worker进程。
- 每台机器上都有对象存储。
- 每台机器上有一个raylet。
- 多个Redis服务(在头节点上)。
要运行一些命令,请在集群中的一个节点上启动Python,然后执行以下操作。
import rayray.init(address="<address>")
现在,您可以定义远程函数并执行任务。例如,要验证是否已加入正确数量的节点,您可以运行以下命令:
import time@ray.remotedef f():time.sleep(0.01)return ray.services.get_node_ip_address()# Get a list of the IP addresses of the nodes that have joined the cluster.set(ray.get([f.remote() for _ in range(1000)]))
停止Ray
当您要停止Ray进程时,请在每个节点上运行ray stop。
在YARN上部署(进行中)
在Kubernetes上部署(进行中)
Warning⚠️:在Kubernetes上运行Ray仍在进行中。
