第2章 欢迎使用 Ray!
欢迎来到 Ray
一个开源框架,助你轻松构建和扩展机器学习及 Python 应用 快速上手 Ray 安装 Ray Ray 示例库
使用 Ray 进行扩展
批量推理 模型训练 超参数调优 模型服务 强化学习
from typing import Dict import numpy as np
import ray
# 第一步:从内存中的 Numpy 数组创建 Ray Dataset。 ds = ray.data.from_numpy(np.asarray(["Complete this", "for me"]))
# 第二步:定义用于推理的 Predictor 类。 class HuggingFacePredictor: def __init__(self): from transformers import pipeline # 初始化预训练的 GPT2 HuggingFace pipeline。 self.model = pipeline("text-generation", model="gpt2")
# 处理单批次数据的推理逻辑。 def __call__(self, batch: Dict[str, np.ndarray]) -> Dict[str, list]: # 获取输入批次的预测结果。 predictions = self.model( list(batch["data"]), max_length=20, num_return_sequences=1) # `predictions` 是一个长度为 1 的列表的列表。例如: # [[{"generated_text": "output_1"}], ..., [{"generated_text": "output_2"}]] # 修改输出格式为: # ["output_1", "output_2"] batch["output"] = [sequences[0]["generated_text"] for sequences in predictions] return batch
# 使用 2 个并行 actor 进行推理。每个 actor 预测 # 不同的数据分区。 # 第三步:将 Predictor 映射到 Dataset 上以获取预测结果。 predictions = ds.map_batches(HuggingFacePredictor, compute=ray.data.ActorPoolStrategy(size=2)) # 第四步:展示一条预测输出。 predictions.show(limit=1)
了解更多关于 Ray Data 示例 from ray.train import ScalingConfig from ray.train.torch import TorchTrainer
# 第一步:像往常一样设置 PyTorch 模型训练。 def train_func(): model = ... train_dataset = ... for epoch in range(num_epochs): ... # 模型训练逻辑
# 第二步:配置 Ray 的 PyTorch Trainer 在 32 个 GPU 上运行。 trainer = TorchTrainer( train_loop_per_worker=train_func, scaling_config=ScalingConfig(num_workers=32, use_gpu=True), datasets={"train": train_dataset}, )
# 第三步:在 32 个 GPU 上运行分布式模型训练。 result = trainer.fit()
了解更多关于 Ray Train 示例 from ray import tune
# 第一步:定义待优化的目标函数。 def objective(config): # 使用 config 中的超参数训练模型 model = train_model( lr=config["lr"], batch_size=config["batch_size"], num_layers=config["num_layers"], ) accuracy = evaluate_model(model) # 向 Tune 报告指标 tune.report(accuracy=accuracy)
# 第二步:定义超参数搜索空间。 search_space = { "lr": tune.loguniform(1e-4, 1e-1), "batch_size": tune.choice([32, 64, 128]), "num_layers": tune.randint(1, 10), }
# 第三步:配置并使用 Ray Tune 运行 1000 个试验。 tuner = tune.Tuner( objective, param_space=search_space, tune_config=tune.TuneConfig(num_samples=1000), )
result_grid = tuner.fit() best_result = result_grid.get_best_result(metric="accuracy", mode="max")
了解更多关于 Ray Tune 示例 from io import BytesIO from fastapi import FastAPI from fastapi.responses import Response import torch
from ray import serve from ray.serve.handle import DeploymentHandle
app = FastAPI()
@serve.deployment(num_replicas=1) @serve.ingress(app) class APIIngress: def __init__(self, diffusion_model_handle: DeploymentHandle) -> None: self.handle = diffusion_model_handle
@app.get( "/imagine", responses={200: {"content": {"image/png": {}}}}, response_class=Response, ) async def generate(self, prompt: str, img_size: int = 512): assert len(prompt), "prompt parameter cannot be empty"
image = await self.handle.generate.remote(prompt, img_size=img_size) file_stream = BytesIO() image.save(file_stream, "PNG") return Response(content=file_stream.getvalue(), media_type="image/png")
@serve.deployment( ray_actor_options={"num_gpus": 1}, autoscaling_config={"min_replicas": 0, "max_replicas": 2}, ) class StableDiffusionV2: def __init__(self): from diffusers import EulerDiscreteScheduler, StableDiffusionPipeline
model_id = "stabilityai/stable-diffusion-2"
scheduler = EulerDiscreteScheduler.from_pretrained( model_id, subfolder="scheduler" ) self.pipe = StableDiffusionPipeline.from_pretrained( model_id, scheduler=scheduler, revision="fp16", torch_dtype=torch.float16 ) self.pipe = self.pipe.to("cuda")
def generate(self, prompt: str, img_size: int = 512): assert len(prompt), "prompt parameter cannot be empty"
with torch.autocast("cuda"): image = self.pipe(prompt, height=img_size, width=img_size).images[0] return image
entrypoint = APIIngress.bind(StableDiffusionV2.bind())
了解更多关于 Ray Serve 快速入门
from ray.rllib.algorithms.ppo import PPOConfig
# 第一步:配置 PPO 运行 64 个并行 worker 从环境中收集样本。 ppo_config = ( PPOConfig() .environment(env="Taxi-v3") .rollouts(num_rollout_workers=64) .framework("torch") .training(model=rnn_lage) )
# 第二步:构建 PPO 算法。 ppo_algo = ppo_config.build()
# 第三步:训练并评估 PPO。 for _ in range(5): print(ppo_algo.train())
ppo_algo.evaluate()
了解更多关于 Ray RLlib 示例
进阶应用 Ray 库 通过高层 Python API,从数据摄入到模型服务,扩展整个 ML 流水线,这些 API 可与流行的生态系统框架集成。 了解更多
Ray 核心
通过简单的基础原语扩展通用 Python 代码,使构建分布式应用程序或自定义平台时拥有高度的控制权。
了解更多
Ray 集群
在 AWS、GCP、Azure 或 Kubernetes 上部署 Ray 集群,以无缝扩展生产环境中的工作负载。
了解更多
参与其中 加入社区 获取支持 为 Ray 做贡献 参加社区活动 在 Slack 上寻找社区 贡献者指南
订阅通讯 在论坛提问 创建拉取请求
在 Twitter 上关注我们 打开 Issue