Communitygithub.com

G1Joshi/Agent-Skills - Ray

Ray分散コンピューティングのエキスパート支援。Ray Core(アクター、タスク)、Ray Train、Ray Tune、Ray Serveをカバー。Pythonの計算処理やMLトレーニングをマルチノードクラスタでスケールさせる際に使用します。

Agent-Skills - Ray とは?

Rayは、AIのためのコンピューティングレイヤーであり、ChatGPTのトレーニングや大規模ワークロードを支えています。このスキルは、Ray分散コンピューティングに特化したエキスパート支援を提供します。Ray Core(タスクとステートフルアクター)、Ray Train(分散MLトレーニング)、Ray Tune(ハイパーパラメータ最適化)、Ray Serve(本番モデルサービング)の主要概念を網羅しています。Pythonの計算負荷の高い処理や機械学習トレーニングを、単一のラップトップから大規模なクラスタまでシームレスにスケールさせる必要がある場合に特に有効です。スキルには、分散タスクの実行、モデルサービングのためのステートフルアクターの使用、並列ハイパーパラメータチューニングの実行に関する具体的なコード例とベストプラクティスが含まれています。また、オブジェクトストアのフル状態やアクターの予期せぬ終了など、一般的な問題のトラブルシューティングガイドも提供します。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/G1Joshi/Agent-Skills/tree/HEAD/skills/ai-ml/ray

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Ray

RayはAIのためのコンピューティングレイヤーです。ChatGPTのトレーニングや大規模ワークロードを支えています。v3.0(2025年)では、効率性が向上し、エージェント向けのMCPサーバーが追加されました。

使用するタイミング

  • 分散Pythonアプリケーション: 計算負荷の高いPythonタスクを、単一のラップトップから大規模なクラウドクラスタまでシームレスにスケーリング。
  • Ray Trainによる分散MLトレーニング: マルチノードでの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("Computed squares:", results)

コアコンセプト

#分散タスクとステートフルアクター

クラスタワーカー間で関数とクラスをスケーリング:

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("Processed Chunks:", results)

# 2. ステートフルリモートクラス(分散アクター)
@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("Final actor count:", 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("Best hyperparameters:", results.get_best_result().config)

一般的なパターン

モデルサービングのためのステートフル分散アクター

問題: 関数呼び出しのたびに大規模なモデル重みをメモリに再ロードする。

解決策: Rayアクターを使用して、リクエスト間でインメモリ状態を保持する:

@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ダッシュボード(ポート8265)を確認して、ノードのCPU/GPU使用率、アクターの配置、オブジェクトストアメモリを監視する。
  • 推奨: 大きな読み取り専用データセットは、Rayプラズマオブジェクトストア(ray.put(data))を介して渡し、繰り返しのシリアライゼーションを防ぐ。
  • 推奨: デコレータでリソース要件を明示的に指定する(@ray.remote(num_cpus=2, num_gpus=1))。
  • 推奨: 本番環境でのマルチモデルマイクロサービスには、組み込みの自動バッチ処理を備えたRay Serveを使用する。
  • 非推奨: ray.get() をリモートタスク内で呼び出さない。ObjectRefを他のリモートタスクに直接渡してパイプライン処理を維持する。
  • 非推奨: 数百万のマイクロタスクを作成しない。細かいタスクをまとめて、スケジューラのオーバーヘッドを最小限に抑える。
  • 非推奨: リモート引数内に、データベース接続や開いているファイルなどの大きなステートフルオブジェクトを渡さない。

トラブルシューティング

エラー原因解決策
RaySystemError: Object store fullタスクが割り当てられた共有メモリプラズマストアよりも多くのデータを生成している。ray.get() を使用して結果を消費するか、大きな配列をディスクストレージに保存する。
Actor died unexpectedlyワーカープロセスが未処理の例外またはOOMでクラッシュした。Rayダッシュボード(http://localhost:8265)でログを確認し、ワーカーRAMを増やす。
Task failed to schedule: Unsatisfiable resource requestクラスタで利用可能な数よりも多くのCPU/GPU(num_gpus=2)を要求した。ray.cluster_resources() で利用可能なリソースを確認する。

参考文献

Individual skills in this repo

This repo contains 11 individual skills — each has its own dedicated page.

G1Joshi/Agent-Skills

Expert Dask distributed computing assistance covering Dask DataFrames, Arrays, Futures, and cluster scaling. Use when analyzing datasets too large for pandas on a single machine or multi-node cluster.

G1Joshi/Agent-Skills

Expert dbt (data build tool) assistance covering SQL modeling, Jinja macros, tests, documentation, and semantic layer. Use when building analytics engineering pipelines on BigQuery, Snowflake, or PostgreSQL.

G1Joshi/Agent-Skills

Expert JAX assistance covering Autograd, XLA compilation (`jit`), vectorization (`vmap`), and parallelization (`pmap`). Use when building high-performance numerical computing and cutting-edge deep learning research.

G1Joshi/Agent-Skills

Expert Git version control assistance covering branching, interactive rebase, cherry-pick, submodules, worktrees, and conflict resolution. Use when managing source code history and collaboration workflows.

G1Joshi/Agent-Skills

Expert K9s CLI assistance covering terminal Kubernetes cluster navigation, real-time log streaming, port forwarding, and pod debugging. Use when managing and troubleshooting Kubernetes clusters with speed.

G1Joshi/Agent-Skills

Expert SWC assistance covering high-performance Rust-based JavaScript/TypeScript compilation, .swcrc configuration, Jest testing via @swc/jest, and minification. Use when replacing Babel with SWC for faster builds, accelerating test execution, or compiling modern ECMAScript features.

G1Joshi/Agent-Skills

Expert Tig assistance covering text-mode interface for Git, interactive staging, commit graph visualization, diff exploration, and blame navigation. Use when navigating Git commit history in the terminal, staging hunks interactively, browsing file changes, or reviewing revisions.

G1Joshi/Agent-Skills

Expert Vim assistance covering modal editing, .vimrc configuration, registers, macros, search/replace, and plugin management via vim-plug. Use when editing text efficiently in terminal environments, writing Vimscript, recording macros, or configuring core Vim settings.

G1Joshi/Agent-Skills

Expert Zed editor assistance covering high-performance Rust-based text editing, multi-buffer editing, language server protocols (LSP), and AI assistant integrations. Use when configuring Zed settings.json, setting up language extensions, collaborating in real-time channels, or optimizing editor startup speed.

G1Joshi/Agent-Skills

Expert Zsh assistance covering shell customization, Oh My Zsh plugins, Zinit plugin manager, prompt engineering (Starship/Powerlevel10k), and shell scripting. Use when configuring .zshrc, writing Zsh automation scripts, optimizing shell startup time, or configuring tab-completion.

G1Joshi/Agent-Skills

Expert [skill-name] assistance covering [feature 1], [feature 2], and [feature 3]. Use when [working with X], [debugging Y], or [implementing Z].

関連スキル