ray
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "ray" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-8d481013b1c113aa77c8887fe8f8b2258ef7386a46c3e040b93a0ae8a5ca0419. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Ray distributed framework: for scaling Python applications from laptop to cluster. Includes Ray Core for distributed computing, Ray Serve for model serving, Ray Tune for hyperparameter optimization, and Ray Data for distributed data processing.
Introduction source: third_party · TerminalSkills · 1.0.0 Reference
SkillPi interpretation
- Tasks
- ray.init() # Connects to or starts a local Ray cluster
- Software, accounts and paid services
- ```yaml
- Testing
- Not tested
Browse files
Frontmatter
name: ray
description: |
Framework for scaling Python applications from a laptop to a cluster. Includes Ray Core
for distributed computing, Ray Serve for model serving, Ray Tune for hyperparameter
optimization, and Ray Data for distributed data processing.
license: Apache-2.0
compatibility: 'python 3.8+, ray 2.9+, Linux/macOS/Windows'
metadata:
author: terminal-skills
version: 1.0.0
category: data-ai
tags:
- distributed-computing
- model-serving
- hyperparameter-tuning
- scaling
- parallel-processingRay
Installation
# Install Ray with all components
pip install "ray[default]"
# Or specific components
pip install "ray[serve]" # Model serving
pip install "ray[tune]" # Hyperparameter tuning
pip install "ray[data]" # Distributed data processing
Ray Core — Distributed Functions
# ray_basics.py — Parallelize Python functions across CPUs/GPUs
import ray
import time
ray.init() # Connects to or starts a local Ray cluster
@ray.remote
def process_item(item: int) -> int:
time.sleep(1) # Simulate work
return item ** 2
# Run 10 tasks in parallel (takes ~1s instead of 10s)
futures = [process_item.remote(i) for i in range(10)]
results = ray.get(futures)
print(f"Results: {results}")
# GPU tasks
@ray.remote(num_gpus=1)
def train_on_gpu(data):
import torch
device = torch.device("cuda")
tensor = torch.tensor(data, device=device)
return tensor.sum().item()
Ray Actors — Stateful Workers
# ray_actors.py — Stateful distributed objects for maintaining state across calls
import ray
@ray.remote
class ModelServer:
def __init__(self, model_name: str):
from transformers import pipeline
self.pipe = pipeline("sentiment-analysis", model=model_name)
self.request_count = 0
def predict(self, text: str) -> dict:
self.request_count += 1
return self.pipe(text)[0]
def get_stats(self) -> dict:
return {"requests": self.request_count}
# Create 3 actor replicas
servers = [ModelServer.remote("distilbert-base-uncased-finetuned-sst-2-english") for _ in range(3)]
# Distribute requests across actors
texts = ["Great product!", "Terrible service", "It's okay"] * 10
futures = [servers[i % 3].predict.remote(text) for i, text in enumerate(texts)]
results = ray.get(futures)
Ray Serve — Model Serving
# serve_model.py — Deploy ML models as scalable HTTP endpoints
from ray import serve
from starlette.requests import Request
@serve.deployment(num_replicas=2, ray_actor_options={"num_gpus": 0.5})
class SentimentService:
def __init__(self):
from transformers import pipeline
self.classifier = pipeline("sentiment-analysis")
async def __call__(self, request: Request) -> dict:
body = await request.json()
text = body.get("text", "")
result = self.classifier(text)[0]
return {"label": result["label"], "score": result["score"]}
app = SentimentService.bind()
serve.run(app, host="0.0.0.0", port=8000)
# Test the endpoint
curl -X POST http://localhost:8000 \
-H "Content-Type: application/json" \
-d '{"text": "Ray Serve is excellent!"}'
Ray Serve — Composition (Multi-Model Pipeline)
# serve_pipeline.py — Chain multiple models in a serving pipeline
from ray import serve
from starlette.requests import Request
@serve.deployment
class Preprocessor:
def preprocess(self, text: str) -> str:
return text.strip().lower()
@serve.deployment
class Classifier:
def __init__(self):
from transformers import pipeline
self.pipe = pipeline("sentiment-analysis")
def classify(self, text: str) -> dict:
return self.pipe(text)[0]
@serve.deployment
class Pipeline:
def __init__(self, preprocessor, classifier):
self.preprocessor = preprocessor
self.classifier = classifier
async def __call__(self, request: Request) -> dict:
body = await request.json()
clean_text = await self.preprocessor.preprocess.remote(body["text"])
result = await self.classifier.classify.remote(clean_text)
return result
preprocessor = Preprocessor.bind()
classifier = Classifier.bind()
app = Pipeline.bind(preprocessor, classifier)
Ray Tune — Hyperparameter Optimization
# tune_experiment.py — Run hyperparameter search across a cluster
from ray import tune
from ray.tune.schedulers import ASHAScheduler
def train_model(config):
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(10, config["hidden_size"]),
nn.ReLU(),
nn.Linear(config["hidden_size"], 1),
)
optimizer = torch.optim.Adam(model.parameters(), lr=config["lr"])
for epoch in range(20):
x = torch.randn(64, 10)
y = torch.randn(64, 1)
loss = nn.MSELoss()(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
tune.report({"loss": loss.item(), "epoch": epoch})
scheduler = ASHAScheduler(max_t=20, grace_period=5, reduction_factor=2)
results = tune.run(
train_model,
config={
"lr": tune.loguniform(1e-4, 1e-1),
"hidden_size": tune.choice([32, 64, 128, 256]),
},
num_samples=20,
scheduler=scheduler,
metric="loss",
mode="min",
resources_per_trial={"cpu": 2, "gpu": 0},
)
best = results.get_best_result()
print(f"Best config: {best.config}")
print(f"Best loss: {best.metrics['loss']:.4f}")
Ray Data — Distributed Processing
# ray_data.py — Process large datasets in parallel with Ray Data
import ray
# Read and process a large dataset
ds = ray.data.read_parquet("s3://my-bucket/data/")
# Map transformations in parallel
def preprocess(batch):
batch["text_length"] = [len(t) for t in batch["text"]]
return batch
processed = ds.map_batches(preprocess, batch_format="pandas")
# Filter
filtered = processed.filter(lambda row: row["text_length"] > 50)
# Write results
filtered.write_parquet("s3://my-bucket/processed/")
print(f"Processed {filtered.count()} records")
Cluster Setup
# ray-cluster.yaml — Ray cluster configuration for Kubernetes
cluster_name: ml-cluster
max_workers: 4
provider:
type: kubernetes
namespace: ray
head_node_type:
node_config:
resources:
cpu: "4"
memory: "16Gi"
worker_node_types:
- name: gpu-worker
min_workers: 0
max_workers: 4
node_config:
resources:
cpu: "8"
memory: "32Gi"
nvidia.com/gpu: "1"
Key Concepts
- Ray Core:
@ray.remoteturns any function/class into a distributed task/actor - Ray Serve: Production model serving with autoscaling, batching, and multi-model composition
- Ray Tune: Hyperparameter search with ASHA, Bayesian optimization, PBT, and more
- Ray Data: Distributed data loading and preprocessing for ML training pipelines
- Autoscaling: Automatically scales workers up/down based on demand
- Resource management: Specify CPU, GPU, and memory requirements per task
Current listing version
1.0.0
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Areas to improve
-
缺少 When to Use 章节 Reported severity: Minor
文档未明确说明何时使用此 Skill,用户可能难以判断适用场景。
Recommendation: 建议在文档开头添加 When to Use 章节,说明适合分布式计算、模型服务、超参数优化等场景。
-
文档较长 Reported severity: Minor
文档约 450 行,可能影响用户阅读体验。
Recommendation: 建议将部分内容拆分为独立文件,或在文档开头添加目录导航。
Highlights
- 提供 Ray 框架的完整使用指南,涵盖分布式计算、模型服务、超参数优化和数据处理
- 包含丰富的代码示例和实际应用场景
- 支持多种部署方式(本地、集群、Kubernetes)
Highlights
- description 在顶层 frontmatter 和 skill_body 内部均有完整描述
- 触发词精准覆盖 Ray 框架的核心功能
- 边界清晰,不易与其他 Skill 重叠
Areas to improve
-
部分代码块未显式处理异常 Reported severity: Minor
如 Ray Serve 的 HTTP 请求未处理网络异常或 JSON 解析错误。
Recommendation: 建议在关键代码块中添加异常处理逻辑,提升执行可靠性。
Highlights
- 文档结构清晰,分 Installation、Ray Core、Ray Actors、Ray Serve、Ray Tune、Ray Data、Cluster Setup、Key Concepts 等章节
- 每部分均有代码示例和说明,便于用户理解
- frontmatter 完整,包含兼容性、许可证、作者等信息
Areas to improve
-
部分代码块未显式处理异常 Reported severity: Minor
如 Ray Serve 的 HTTP 请求未处理网络异常或 JSON 解析错误。
Recommendation: 建议在关键代码块中添加异常处理逻辑,提升执行可靠性。
Highlights
- 所有代码示例均包含必要的依赖安装和错误处理
- 工具来源明确(Ray 官方),参数正确
- 覆盖主要异常场景,如资源分配、任务调度
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Install or fetch external dependencies
Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.
Mentioned in main document · lines 27, 30, 31, 32
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- localhost
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
```yaml
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.