Ray
Ray 是 AI 的计算层。它为 ChatGPT 训练和大规模工作负载提供支持。v3.0(2025)提升了效率并增加了用于智能体的 MCP 服务器。
何时使用
- 分布式 Python 应用:将计算密集型 Python 任务从单台笔记本电脑无缝扩展到大型云集群。
- 使用 Ray Train 进行分布式机器学习训练:编排多节点 PyTorch、XGBoost 和 LightGBM 训练任务。
- 使用 Ray Serve 进行生产模型服务:为 LLM 和微服务模型流水线提供动态自动缩放。
- 使用 Ray Tune 进行超参数优化:跨数百个工作节点运行贝叶斯、Optuna 和基于种群的训练搜索。
快速入门
import ray
ray.init()
# 远程分布式任务
@ray.remote
def square(x):
return x * x
# 在集群中并行启动任务
futures = [square.remote(i) for i in range(10)]
results = ray.get(futures)
print("计算出的平方值:", results)
核心概念
#分布式任务与有状态 Actor
在集群工作节点间扩展函数和类:
import ray
import time
# 初始化本地或连接到远程 Ray 集群
ray.init(ignore_reinit_error=True)
# 1. 无状态远程函数(分布式任务)
@ray.remote
def process_data_chunk(chunk_id: int) -> dict:
time.sleep(0.5) # 模拟 CPU/IO 密集型计算
return {"chunk_id": chunk_id, "processed_items": 1000 * chunk_id}
# 在集群上并发启动任务
futures = [process_data_chunk.remote(i) for i in range(8)]
results = ray.get(futures) # 收集结果
print("处理的数据块:", results)
# 2. 有状态远程类(分布式 Actor)
@ray.remote
class GlobalCounter:
def __init__(self):
self.count = 0
def increment(self) -> int:
self.count += 1
return self.count
counter_actor = GlobalCounter.remote()
inc_futures = [counter_actor.increment.remote() for _ in range(5)]
print("最终 Actor 计数:", ray.get(inc_futures[-1]))
#使用 Ray Serve 进行生产模型服务
部署具有动态请求批处理的可扩展 REST 端点:
from ray import serve
import torch
from transformers import pipeline
@serve.deployment(num_replicas=2, ray_actor_options={"num_cpus": 1, "num_gpus": 0})
class SentimentClassifier:
def __init__(self):
self.classifier = pipeline("sentiment-analysis")
async def __call__(self, request):
json_data = await request.json()
text = json_data.get("text", "")
return self.classifier(text)
app = SentimentClassifier.bind()
# serve.run(app)
#使用 Ray Tune 进行分布式超参数调优
运行并行超参数试验:
from ray import tune
def training_function(config):
# 模拟模型训练
for step in range(10):
intermediate_score = config["alpha"] * step + config["beta"]
tune.report(loss=1.0 / (intermediate_score + 0.1))
search_space = {
"alpha": tune.uniform(0.1, 1.0),
"beta": tune.choice([1, 2, 5])
}
tuner = tune.Tuner(
training_function,
param_space=search_space,
tune_config=tune.TuneConfig(num_samples=10, metric="loss", mode="min")
)
results = tuner.fit()
print("最佳超参数:", results.get_best_result().config)
常见模式
用于模型服务的有状态分布式 Actor
问题:每次函数调用时都要将大型模型权重重新加载到内存中。
解决方案: 使用 Ray Actor 在请求之间保持内存状态:
@ray.remote(num_gpus=1)
class ModelServer:
def __init__(self):
# 一次性将权重加载到 GPU VRAM
self.model = load_large_model()
def predict(self, sample):
return self.model(sample)
server_actor = ModelServer.remote()
prediction = ray.get(server_actor.predict.remote(sample_data))
最佳实践(2026)
- 务必 检查 Ray Dashboard(端口 8265)以监控节点 CPU/GPU 利用率、Actor 位置和对象存储内存。
- 务必 通过 Ray plasma 对象存储(
ray.put(data))传递大型只读数据集,以防止重复序列化。 - 务必 在装饰器中显式指定资源需求(
@ray.remote(num_cpus=2, num_gpus=1))。 - 务必 使用 Ray Serve 进行生产多模型微服务,内置自动批处理。
- 请勿 在远程任务内部调用
ray.get();直接将ObjectRef传递给其他远程任务以保持流水线。 - 请勿 创建数百万个微任务;将细粒度任务批量组合以最小化调度开销。
- 请勿 在远程参数中传递大型有状态对象(例如数据库连接或打开的文件)。
故障排查
| 错误 | 原因 | 解决方案 |
|---|---|---|
RaySystemError: Object store full | 任务产生的数据超出了分配的共享内存 plasma 存储。 | 使用 ray.get() 消费结果,或将大型数组存储到磁盘存储中。 |
Actor died unexpectedly | 工作进程因未处理的异常或 OOM 崩溃。 | 检查 Ray Dashboard(http://localhost:8265)中的日志,并增加工作节点 RAM。 |
Task failed to schedule: Unsatisfiable resource request | 请求的 CPU/GPU(num_gpus=2)超过了集群可用资源。 | 通过 ray.cluster_resources() 验证可用资源。 |