进阶 ray.io 2026-11-20 06:00:47 · 10 阅读

第12章 Ray 入门指南

入门指南

Ray 是一个用于扩展 AI 和 Python 应用规模的开源统一框架。它提供简单通用的 API,可构建分布式应用,规模可从笔记本电脑无缝扩展至集群。

什么是 Ray?

Ray 通过提供以下功能简化分布式计算:
  • 可扩展计算原语:任务(Tasks)和 Actor,实现无痛并行编程
  • 专用 AI 库:针对数据处理、模型训练、超参数调优、模型服务等常见 ML 场景的工具
  • 统一资源管理:从笔记本到云端的无缝扩展,自动处理资源

选择你的路径

选择符合你需求的指南:
  • 扩展 ML 工作负载:Ray Libraries 快速入门
  • 扩展通用 Python 应用:Ray Core 快速入门
  • 部署到云端:Ray Clusters 快速入门
  • 调试与监控应用:调试与监控快速入门

Ray AI 库快速入门

使用独立库处理 ML 工作负载。每个库专精于 ML 工作流的特定环节,从数据处理到模型服务。点击下拉菜单选择你的工作负载。

数据:AI 工作负载的可扩展数据处理

Ray Data 为 AI 工作负载提供分布式数据处理能力,高效地将数据流通过数据管道。

下面展示如何使用 Ray Data 扩展离线推理和训练数据摄取。

注意
运行此示例需安装 Ray Data:
pip install -U "ray[data]"
from typing import Dict
import numpy as np
import ray

# 从磁盘文件、Python 对象或 S3 等云存储创建数据集。
ds = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv")

# 应用函数转换数据。Ray Data 并行执行转换。
def compute_area(batch: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
    length = batch["petal length (cm)"]
    width = batch["petal width (cm)"]
    batch["petal area (cm^2)"] = length * width
    return batch

transformed_ds = ds.map_batches(compute_area, batch_size="auto")

# 遍历数据批次。
for batch in transformed_ds.iter_batches(batch_size=4):
    print(batch)

# 保存数据集内容到磁盘文件或云存储。
transformed_ds.write_parquet("local:///tmp/iris/")
了解更多关于 Ray Data

训练:分布式模型训练

Ray Train 简化分布式模型训练。它抽象了在 PyTorch 和 TensorFlow 等流行框架上搭建分布式训练的复杂性。

PyTorch

本示例展示如何使用 Ray Train 配合 PyTorch。运行此示例需安装 Ray Train 和 PyTorch 包:

注意
pip install -U "ray[train]" torch torchvision

设置数据集和模型。

import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor

def get_dataset():
    return datasets.FashionMNIST(
        root="/tmp/data",
        train=True,
        download=True,
        transform=ToTensor(),
    )

class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28 * 28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
        )

    def forward(self, inputs):
        inputs = self.flatten(inputs)
        logits = self.linear_relu_stack(inputs)
        return logits

定义单 Worker PyTorch 训练函数。

def train_func():
    num_epochs = 3
    batch_size = 64

    dataset = get_dataset()
    dataloader = DataLoader(dataset, batch_size=batch_size)

    model = NeuralNetwork()

    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

    for epoch in range(num_epochs):
        for inputs, labels in dataloader:
            optimizer.zero_grad()
            pred = model(inputs)
            loss = criterion(pred, labels)
            loss.backward()
            optimizer.step()
        print(f"epoch: {epoch}, loss: {loss.item()}")

通过 train_func() 执行此训练函数。

将此函数转换为分布式多 Worker 训练函数。
使用 ray.train.torch.prepare_model 和 ray.train.torch.prepare_data_loader 工具函数为分布式训练设置模型和数据。
这会自动用 DistributedDataParallel 包装模型并将其放置到正确设备上,同时为 DataLoader 添加 DistributedSampler。

import ray.train.torch

def train_func_distributed():
    num_epochs = 3
    batch_size = 64

    dataset = get_dataset()
    dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
    dataloader = ray.train.torch.prepare_data_loader(dataloader)

    model = NeuralNetwork()
    model = ray.train.torch.prepare_model(model)

    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

    for epoch in range(num_epochs):
        if ray.train.get_context().get_world_size() > 1:
            dataloader.sampler.set_epoch(epoch)

        for inputs, labels in dataloader:
            optimizer.zero_grad()
            pred = model(inputs)
            loss = criterion(pred, labels)
            loss.backward()
            optimizer.step()
        print(f"epoch: {epoch}, loss: {loss.item()}")

实例化包含 4 个 Worker 的 TorchTrainer,用它运行新的训练函数。

from ray.train.torch import TorchTrainer
from ray.train import ScalingConfig

# GPU 训练时,将 `use_gpu` 设为 True。
use_gpu = False

trainer = TorchTrainer(
    train_func_distributed,
    scaling_config=ScalingConfig(num_workers=4, use_gpu=use_gpu)
)

results = trainer.fit()

若需使用 GPU 加速训练,请确保已配置 GPU,然后将 use_gpu 设为 True。若无 GPU 环境,Anyscale 提供集成自动扩展 GPU 集群的开发工作空间以满足此需求。

TensorFlow

本示例展示如何使用 Ray Train 搭建基于 Keras 的多 Worker 训练。
运行此示例需安装 Ray Train 和 TensorFlow 包:

注意
pip install -U "ray[train]" tensorflow

设置数据集和模型。

import os
os.environ["TF_USE_LEGACY_KERAS"] = "1"

import sys
import numpy as np

if sys.version_info >= (3, 12):
    # 由于 keras 兼容性问题,Python 3.12 未安装 Tensorflow。
    sys.exit(0)
else:
    import tensorflow as tf

def mnist_dataset(batch_size):
    (x_train, y_train), _ = tf.keras.datasets.mnist.load_data()
    # `x` 数组为 uint8,值域 [0, 255]。
    # 需转换为 float32,值域 [0, 1]。
    x_train = x_train / np.float32(255)
    y_train = y_train.astype(np.int64)
    train_dataset = tf.data.Dataset.from_tensor_slices(
        (x_train, y_train)).shuffle(60000).repeat().batch(batch_size)
    return train_dataset


def build_and_compile_cnn_model():
    model = tf.keras.Sequential([
        tf.keras.layers.InputLayer(input_shape=(28, 28)),
        tf.keras.layers.Reshape(target_shape=(28, 28, 1)),
        tf.keras.layers.Conv2D(32, 3, activation='relu'),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(128, activation='relu'),
        tf.keras.layers.Dense(10)
    ])
    model.compile(
        loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
        optimizer=tf.keras.optimizers.SGD(learning_rate=0.001),
        metrics=['accuracy'])
    return model

定义单 Worker TensorFlow 训练函数。

def train_func():
    batch_size = 64
    single_worker_dataset = mnist_dataset(batch_size)
    single_worker_model = build_and_compile_cnn_model()
    single_worker_model.fit(single_worker_dataset, epochs=3, steps_per_epoch=70)

通过 train_func() 执行此训练函数。

将此函数转换为分布式多 Worker 训练函数。

设置全局 Batch Size - 每个 Worker 处理的 Batch 大小与单 Worker 代码相同。
选择 TensorFlow 分布式训练策略。此示例使用 MultiWorkerMirroredStrategy。

import json
import os

def train_func_distributed():
    per_worker_batch_size = 64
    # 此环境变量由 Ray Train 设置。
    tf_config = json.loads(os.environ['TF_CONFIG'])
    num_workers = len(tf_config['cluster']['worker'])

    strategy = tf.distribute.MultiWorkerMirroredStrategy()

    global_batch_size = per_worker_batch_size * num_workers
    multi_worker_dataset = mnist_dataset(global_batch_size)

    with strategy.scope():
        # 模型构建/编译需在 `strategy.scope()` 内。
        multi_worker_model = build_and_compile_cnn_model()

    multi_worker_model.fit(multi_worker_dataset, epochs=3, steps_per_epoch=70)

实例化包含 4 个 Worker 的 TensorflowTrainer,用它运行新的训练函数。

from ray.train.tensorflow import TensorflowTrainer
from ray.train import ScalingConfig

# GPU 训练时,将 `use_gpu` 设为 True。
use_gpu = False

trainer = TensorflowTrainer(train_func_distributed, scaling_config=ScalingConfig(num_workers=4, use_gpu=use_gpu))

trainer.fit()

若需使用 GPU 加速训练,请确保已配置 GPU,然后将 use_gpu 设为 True。若无 GPU 环境,Anyscale 提供集成自动扩展 GPU 集群的开发工作空间以满足此需求。

了解更多关于 Ray Train

调优:大规模超参数调优

Ray Tune 是任意规模超参数调优库。它使用高效分布式搜索算法自动为模型寻找最佳超参数。
通过 Tune,可用不到 10 行代码启动多节点分布式超参数扫描,支持 PyTorch、TensorFlow、Keras 等任意深度学习框架。

注意
运行此示例需安装 Ray Tune:
pip install -U "ray[tune]"

本示例运行小型网格搜索,使用迭代训练函数。

from ray import tune


def objective(config):  # ①
    score = config["a"] ** 2 + config["b"]
    return {"score": score}


search_space = {  # ②
    "a": tune.grid_search([0.001, 0.01, 0.1, 1.0]),
    "b": tune.choice([1, 2, 3]),
}

tuner = tune.Tuner(objective, param_space=search_space)  # ③

results = tuner.fit()
print(results.get_best_result(metric="score", mode="min").config)

若已安装 TensorBoard(pip install tensorboard),可自动可视化所有试验结果:

tensorboard --logdir ~/ray_results
了解更多关于 Ray Tune

服务:可扩展模型服务

Ray Serve 为 ML 模型和业务逻辑提供可扩展、可编程的服务。以生产级性能部署任意框架的模型。

注意
运行此示例需安装 Ray Serve 和 scikit-learn:
pip install -U "ray[serve]" scikit-learn

本示例服务 scikit-learn 梯度提升分类器。

import requests
from starlette.requests import Request
from typing import Dict

from sklearn.datasets import load_iris
from sklearn.ensemble import GradientBoostingClassifier

from ray import serve


# 训练模型。
iris_dataset = load_iris()
model = GradientBoostingClassifier()
model.fit(iris_dataset["data"], iris_dataset["target"])


@serve.deployment
class BoostingModel:
    def __init__(self, model):
        self.model = model
        self.label_list = iris_dataset["target_names"].tolist()

    async def __call__(self, request: Request) -> Dict:
        payload = (await request.json())["vector"]
        print(f"Received http request with data {payload}")

        prediction = self.model.predict([payload])[0]
        human_name = self.label_list[prediction]
        return {"result": human_name}


# 部署模型。
serve.run(BoostingModel.bind(model), route_prefix="/iris")

# 查询它!
sample_request_input = {"vector": [1.2, 1.0, 1.1, 0.9]}
response = requests.get(
    "http://localhost:8000/iris", json=sample_request_input)
print(response.text)

响应显示 {"result": "versicolor"}。

了解更多关于 Ray Serve

RLlib:工业级强化学习

RLlib 是强化学习(RL)库,提供流行 RL 算法的高性能实现,支持多种训练环境。RLlib 具备高可扩展性和统一 API,适用于各类工业和研究应用。

注意
运行此示例需安装 rllib 和 tensorflow 或 pytorch:
pip install -U "ray[rllib]" tensorflow # 或 torch

系统可能还需安装 CMake。
import gymnasium as gym
import numpy as np
import torch
from typing import Dict, Tuple, Any, Optional

from ray.rllib.algorithms.ppo import PPOConfig


# 使用 python 和 Farama-Foundation 的 gymnasium API 定义问题:
class SimpleCorridor(gym.Env):
    """走廊环境,Agent 需学会向右移动到达出口。

    ---------------------
    | S | 1 | 2 | 3 | G |   S=起点; G=目标; corridor_length=5
    ---------------------

    动作:
        0: 左移
        1: 右移

    观测:
        单个浮点数,代表 Agent 当前位置(索引),
        从 0.0 开始,到 corridor_length 结束

    奖励:
        每步 -0.1
        到达目标 +1.0

    回合终止:
        Agent 到达目标(位置 >= corridor_length)
    """

    def __init__(self, config):
        self.end_pos = config["corridor_length"]
        self.cur_pos = 0.0
        self.action_space = gym.spaces.Discrete(2)  # 0=左, 1=右
        self.observation_space = gym.spaces.Box(0.0, self.end_pos, (1,), np.float32)

    def reset(
        self, *, seed: Optional[int] = None, options: Optional[Dict] = None
    ) -> Tuple[np.ndarray, Dict]:
        """为新回合重置环境。

        参数:
            seed: 用于可重现性的随机种子
            options: 额外选项(此环境未使用)

        返回:
            新回合的初始观测和信息字典。
        """
        super().reset(seed=seed)  # 若提供 seed 则初始化 RNG
        self.cur_pos = 0.0
        # 返回初始观测。
        return np.array([self.cur_pos], np.float32), {}

    def step(self, action: int) -> Tuple[np.ndarray, float, bool, bool, Dict]:
        """基于给定动作在环境中执行一步。

        参数:
            action: 0 为左移,1 为右移

        返回:
            (观测, 奖励, 终止, 截断, 信息) 元组:
                观测:Agent 新位置
                奖励:执行动作所得奖励(-0.1 或 +1.0)
                终止:回合是否结束(到达目标)
                截断:回合是否被截断(此处始终为 False)
                信息:额外信息(空字典)
        """
        # 若动作为 0 且不在最左位置,则左移
        if action == 0 and self.cur_pos > 0:
            self.cur_pos -= 1
        # 若动作为 1,则右移
        elif action == 1:
            self.cur_pos += 1
        # 到达走廊末端(目标)时设置 `terminated` 标志。
        terminated = self.cur_pos >= self.end_pos
        truncated = False
        # 到达目标 +1,否则 -0.1。
        reward = 1.0 if terminated else -0.1
        return np.array([self.cur_pos], np.float32), reward, terminated, truncated, {}


# 从 PPOConfig 对象创建 RLlib 算法实例。
print("Setting up the PPO configuration...")
config = (
    PPOConfig().environment(
        # 要使用的 Env 类(我们的自定义 gymnasium 环境)。
        SimpleCorridor,
        # 传递给自定义环境构造函数的配置字典。
        # 使用包含 20 个格子的走廊(含起点和目标)。
        env_config={"corridor_length": 20},
    )
    # 并行化环境 rollout 以加快训练。
    .env_runners(num_env_runners=3)
    # 此简单任务使用较小网络
    .training(model={"fcnet_hiddens": [64, 64]})
)

# 从配置构建实际的 PPO 算法对象。
algo = config.build_algo()
rl_module = algo.get_module()

# 训练 n 次迭代并报告结果(平均回合奖励)。
# 最优奖励计算:
# - 到达目标至少需 19 步(从位置 0 到 19)
# - 每步(除最后一步)奖励 -0.1:18 * (-0.1) = -1.8
# - 最后一步奖励 +1.0
# - 总最优奖励:-1.8 + 1.0 = -0.8
print("\nStarting training loop...")
for i in range(5):
    results = algo.train()

    # 记录训练结果中的指标
    print(f"Iteration {i+1}")
    print(f"  Training metrics: {results['env_runners']}")

# 保存训练好的算法(可选)
checkpoint_dir = algo.save()
print(f"\nSaved model checkpoint to: {checkpoint_dir}")

print("\nRunning inference with the trained policy...")
# 创建较短走廊的测试环境以验证 Agent 行为
env = SimpleCorridor({"corridor_length": 10})
# 获取初始观测(应为:[0.0] 起点位置)。
obs, info = env.reset()
terminated = truncated = False
total_reward = 0.0
step_count = 0

# 播放一个回合并记录 Agent 轨迹
print("\nAgent trajectory:")
positions = [float(obs[0])]  # 记录位置用于可视化

while not terminated and not truncated and step_count < 1000:
    # 基于当前观测计算动作
    action_logits = rl_module.forward_inference(
        {"obs": torch.from_numpy(obs).unsqueeze(0)}
    )["action_dist_inputs"].numpy()[
        0
    ]  # [0]:批次维度=1

    # 获取概率最高的动作
    action = np.argmax(action_logits)

    # 记录 Agent 决策
    action_name = "LEFT" if action == 0 else "RIGHT"
    print(f"  Step {step_count}: Position {obs[0]:.1f}, Action: {action_name}")

    # 在环境中应用计算出的动作
    obs, reward, terminated, truncated, info = env.step(action)
    positions.append(float(obs[0]))

    # 累加奖励
    total_reward += reward
    step_count += 1

# 报告最终结果
print(f"\nEpisode complete:")
print(f"  Steps taken: {step_count}")
print(f"  Total reward: {total_reward:.2f}")
print(f"  Final position: {obs[0]:.1f}")

# 验证 Agent 是否学会最优策略
if total_reward > -0.5 and obs[0] >= 9.0:
    print("  Success! The agent has learned the optimal policy (always move right).")
else:
    print("  Failure! The agent didn't reach the goal within 1000 timesteps.")
了解更多关于 Ray RLlib

Ray Core 快速入门


Ray Core 提供简单的基础原语,用于构建和运行分布式应用。你只需几行代码,即可将普通的 Python 或 Java 函数和类转化为分布式的无状态任务(tasks)和有状态角色(actors)。 以下示例展示了如何: * 将 Python 函数转换为 Ray 任务以并行执行 * 将 Python 类转换为 Ray 角色以进行分布式有状态计算 核心:使用 Ray 任务并行化函数 Python 注意 要运行此示例,请安装 Ray Core: `pip install -U "ray"` 导入 Ray 并使用 `ray.init()` 初始化。 然后使用 `@ray.remote` 装饰函数,声明需要远程执行该函数。 最后,使用 `.remote()` 调用函数,而不是直接调用。 这种远程调用会返回一个未来对象(future),即 Ray 对象引用,你可以随后使用 `ray.get` 获取其值。 ```python import ray ray.init() @ray.remote def f(x): return x * x futures = [f.remote(i) for i in range(4)] print(ray.get(futures)) # [0, 1, 4, 9] ``` Java 注意 要运行此示例,请在项目中添加 ray-api 和 ray-runtime 依赖。 使用 Ray.init 初始化 Ray 运行时。 然后使用 Ray.task(...).remote() 将任意 Java 静态方法转换为 Ray 任务。 任务在远程工作进程异步执行。远程方法返回一个 ObjectRef,你可以使用 get 获取实际结果。 ```java import io.ray.api.ObjectRef; import io.ray.api.Ray; import java.util.ArrayList; import java.util.List; public class RayDemo { public static int square(int x) { return x * x; } public static void main(String[] args) { // Initialize Ray runtime. Ray.init(); List> objectRefList = new ArrayList<>(); // Invoke the `square` method 4 times remotely as Ray tasks. // The tasks run in parallel in the background. for (int i = 0; i < 4; i++) { objectRefList.add(Ray.task(RayDemo::square, i).remote()); } // Get the actual results of the tasks. System.out.println(Ray.get(objectRefList)); // [0, 1, 4, 9] } } ``` 上述代码块中定义了一些 Ray 任务。虽然它们非常适合无状态操作,但有时你需要维护应用的状态。你可以使用 Ray 角色来实现这一点。 了解更多关于 Ray Core 的信息 核心:使用 Ray 角色并行化类 Ray 提供角色,允许你并行化 Python 或 Java 中的类实例。 当你实例化一个 Ray 角色类时,Ray 会在集群中启动该类的一个远程实例。该角色随后可以执行远程方法调用并维护其内部状态。 Python 注意 要运行此示例,请安装 Ray Core: `pip install -U "ray"` ```python import ray ray.init() # Only call this once. @ray.remote class Counter(object): def __init__(self): self.n = 0 def increment(self): self.n += 1 def read(self): return self.n counters = [Counter.remote() for i in range(4)] [c.increment.remote() for c in counters] futures = [c.read.remote() for c in counters] print(ray.get(futures)) # [1, 1, 1, 1] ``` Java 注意 要运行此示例,请在项目中添加 ray-api 和 ray-runtime 依赖。 ```java import io.ray.api.ActorHandle; import io.ray.api.ObjectRef; import io.ray.api.Ray; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class RayDemo { public static class Counter { private int value = 0; public void increment() { this.value += 1; } public int read() { return this.value; } } public static void main(String[] args) { // Initialize Ray runtime. Ray.init(); List> counters = new ArrayList<>(); // Create 4 actors from the `Counter` class. // These run in remote worker processes. for (int i = 0; i < 4; i++) { counters.add(Ray.actor(Counter::new).remote()); } // Invoke the `increment` method on each actor. // This sends an actor task to each remote actor. for (ActorHandle counter : counters) { counter.task(Counter::increment).remote(); } // Invoke the `read` method on each actor, and print the results. List> objectRefList = counters.stream() .map(counter -> counter.task(Counter::read).remote()) .collect(Collectors.toList()); System.out.println(Ray.get(objectRefList)); // [1, 1, 1, 1] } } ``` 了解更多关于 Ray Core 的信息 Ray 集群快速入门 你可以将应用部署在 AWS、GCP、Azure 等 Ray 集群上,通常只需对现有代码做极少修改。 集群:在 AWS 上启动 Ray 集群 Ray 程序可以在单台机器上运行,也可以无缝扩展到大型集群。 注意 要运行此示例,请安装以下依赖: `pip install -U "ray[default]" boto3` 如果尚未配置,请按照 boto3 文档说明配置你的凭证。 以下是一个简单示例,它会等待各个节点加入集群。 `example.py` ```python import sys import time from collections import Counter import ray @ray.remote def get_host_name(x): import platform import time time.sleep(0.01) return x + (platform.node(),) def wait_for_nodes(expected): # Wait for all nodes to join the cluster. while True: num_nodes = len(ray.nodes()) if num_nodes < expected: print( "{} nodes have joined so far, waiting for {} more.".format( num_nodes, expected - num_nodes ) ) sys.stdout.flush() time.sleep(1) else: break def main(): wait_for_nodes(4) # Check that objects can be transferred from each node to each other node. for i in range(10): print("Iteration {}".format(i)) results = [get_host_name.remote(get_host_name.remote(())) for _ in range(100)] print(Counter(ray.get(results))) sys.stdout.flush() print("Success!") sys.stdout.flush() time.sleep(20) if __name__ == "__main__": ray.init(address="localhost:6379") main() ``` 你也可以从 GitHub 仓库下载此示例。 将其本地保存为 `example.py` 文件。 要在云端执行此脚本,请下载以下配置文件, 或在此处复制: `cluster.yaml` ```yaml # An unique identifier for the head node and workers of this cluster. cluster_name: aws-example-minimal # Cloud-provider specific configuration. provider: type: aws region: us-west-2 # The maximum number of workers nodes to launch in addition to the head # node. max_workers: 3 # Tell the autoscaler the allowed node types and the resources they provide. # The key is the name of the node type, which is for debugging purposes. # The node config specifies the launch config and physical instance type. available_node_types: ray.head.default: # The node type's CPU and GPU resources are auto-detected based on AWS instance type. # If desired, you can override the autodetected CPU and GPU resources advertised to the autoscaler. # You can also set custom resources. # For example, to mark a node type as having 1 CPU, 1 GPU, and 5 units of a resource called "custom", set # resources: {"CPU": 1, "GPU": 1, "custom": 5} resources: {} # Provider-specific config for this node type, e.g., instance type. By default # Ray auto-configures unspecified fields such as SubnetId and KeyName. # For more documentation on available fields, see # http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances node_config: InstanceType: m5.large ray.worker.default: # The minimum number of worker nodes of this type to launch. # This number should be >= 0. min_workers: 3 # The maximum number of worker nodes of this type to launch. # This parameter takes precedence over min_workers. max_workers: 3 # The node type's CPU and GPU resources are auto-detected based on AWS instance type. # If desired, you can override the autodetected CPU and GPU resources advertised to the autoscaler. # You can also set custom resources. # For example, to mark a node type as having 1 CPU, 1 GPU, and 5 units of a resource called "custom", set # resources: {"CPU": 1, "GPU": 1, "custom": 5} resources: {} # Provider-specific config for this node type, e.g., instance type. By default # Ray auto-configures unspecified fields such as SubnetId and KeyName. # For more documentation on available fields, see # http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances node_config: InstanceType: m5.large ``` 假设你将此配置保存在名为 `cluster.yaml` 的文件中,你可以按以下方式启动 AWS 集群: `ray submit cluster.yaml example.py --start` 了解更多关于在 AWS、GCP、Azure 等平台启动 Ray 集群的信息 集群:在 Kubernetes 上启动 Ray 集群 Ray 程序可以在单节点 Kubernetes 集群上运行,也可以无缝扩展到更大规模的集群。 了解更多关于在 Kubernetes 上启动 Ray 集群的信息 集群:在 Anyscale 上启动 Ray 集群 Anyscale 是 Ray 背后的公司。Anyscale 平台在 AWS、GCP、Azure 或本地 Kubernetes 集群上提供企业级 Ray 部署。 在 Anyscale 上试用 Ray 调试和监控快速入门 使用内置的可观测性工具来监控和调试 Ray 应用程序及集群。这些工具有助于你理解应用性能并识别瓶颈。 Ray 仪表盘:用于监控和调试 Ray 的 Web GUI Ray 仪表盘提供了一个可视化界面,显示实时系统指标、节点级资源监控、作业分析和任务可视化。该仪表盘旨在帮助用户理解 Ray 应用的性能并识别潜在问题。 注意 要开始使用仪表盘,请按以下方式安装默认版本: `pip install -U "ray[default]"` 运行 Ray 脚本时,仪表盘会自动可用。通过默认 URL http://localhost:8265 访问仪表盘。 了解更多关于 Ray 仪表盘的信息 Ray 状态 API:通过 CLI 访问集群状态 Ray 状态 API 允许用户方便地通过 CLI 或 Python SDK 访问 Ray 的当前状态(快照)。 注意 要开始使用状态 API,请按以下方式安装默认版本: `pip install -U "ray[default]"` 运行以下代码。 ```python import ray import time ray.init(num_cpus=4) @ray.remote def task_running_300_seconds(): print("Start!") time.sleep(300) @ray.remote class Actor: def __init__(self): print("Actor created") # Create 2 tasks tasks = [task_running_300_seconds.remote() for _ in range(2)] # Create 2 actors actors = [Actor.remote() for _ in range(2)] ray.get(tasks) ``` 在终端中使用 `ray summary tasks` 查看 Ray 任务的汇总统计信息。 `ray summary tasks` ``` ======== Tasks Summary: 2022-07-22 08:54:38.332537 ======== Stats: ------------------------------------ total_actor_scheduled: 2 total_actor_tasks: 0 total_tasks: 2 Table (group by func_name): ------------------------------------ FUNC_OR_CLASS_NAME STATE_COUNTS TYPE 0 task_running_300_seconds RUNNING: 2 NORMAL_TASK 1 Actor.__init__ FINISHED: 2 ACTOR_CREATION_TASK ``` 了解更多关于 Ray 状态 API 的信息 更多资源 Ray 拥有丰富的生态系统资源,帮助你更深入地了解分布式计算和 AI 扩展。 博客与新闻 * 现代并行和分布式 Python:Ray 快速教程 * 为什么每个 Python 开发者都会爱上 Ray * Ray:用于 AI 的分布式系统(伯克利人工智能研究,BAIR) * 无需 Python Multiprocessing 实现 10 倍速度的并行 Python * 使用 Ray 在 15 行 Python 代码中实现参数服务器 * Ray 分布式 AI 框架课程 * RayOnSpark:使用 Ray 和 Analytics Zoo 在大数据集群上运行新兴 AI 应用 * Ray 早期用户技巧 * Tune:适用于任意规模的快速超参数调整的 Python 库 * 使用 Ray Tune 进行前沿超参数调整 * 新库瞄准高速强化学习 * 扩展多智能体强化学习 * 使用 Keras 和 Tensorflow Eager 实现函数式强化学习 * 如何通过一行代码将 Pandas 速度提升 4 倍 * 快速技巧——使用 Modin 加速 Pandas * Ray 博客 视频 * 使用 Ray Data 统一大规模数据预处理和机器学习流水线 | PyData 2021(幻灯片) * 使用 Ray 实现任意规模编程 | SF Python Meetup 2019年9月 * 用于强化学习的 Ray | Data Council 2019 * 使用 Modin 扩展交互式 Pandas 工作流 * Ray:用于 AI 的分布式执行框架 | SciPy 2018 * Ray:用于强化学习应用的集群计算引擎 | Spark Summit * RLlib:Ray 强化学习库 | RISECamp 2018 * 实现分布式强化学习中的组合 | Spark Summit 2018 * Tune:分布式超参数搜索 | RISECamp 2018 幻灯片 * 在 UC Berkeley DS100 上的演讲 * 2019年10月的演讲 * 在 RISECamp 2019 上的演讲 论文 * Ray 2.0 架构白皮书 * Ray 1.0 架构白皮书(旧) * Exoshuffle:Ray 中的大规模数据 Shuffle * RLlib 论文 * RLlib 流程论文 * Tune 论文 * Ray 论文(旧) * Ray HotOS 论文(旧) 如果你遇到技术问题,请在 Ray 讨论论坛发帖。对于一般问题、公告和社区讨论,请加入 Ray 的 Slack 社区。

评论 (0)