ray-data について
Ray Dataは、MLやAIワークロード向けの分散データ処理ライブラリです。ストリーミング実行、GPU変換、複数のデータ形式に対応し、単一マシンからクラスターまで拡張できます。
主な機能
- 01メモリを超えるデータのストリーム処理
- 02分散データ変換とフィルタリング
- 03GPUアクセラレーション変換
- 04複数形式の読み書き
- 05PyTorchとTensorFlowとの連携
活用シーン
- 01MLトレーニング向け大規模データの準備
- 02分散プリプロセスのパイプライン構築
- 03バッチ推論ワークロードの実行
- 04画像・音声・動画データの処理
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ orchestra-research/ ai-research-skills --skill ray-dataインストール後、Claude Code で/ray-dataを入力して読み込まれたか確認します。
同梱ファイルreferences/integration.mdreferences/transformations.md
詳細
Ray Data - スケーラブルなMLデータ処理
MLおよびAIワークロード向けの分散データ処理ライブラリです。
Ray Dataを使用するタイミング
次の場合はRay Dataを使用してください:
- MLトレーニング用の大規模なデータセット(>100GB)を処理する場合
- クラスター全体で分散データ前処理を行う必要がある場合
- バッチ推論パイプラインを構築する場合
- マルチモーダルデータ(画像、音声、動画)を読み込む場合
- データ処理をノートPCからクラスターへスケールする場合
主な機能:
- ストリーミング実行:メモリ容量を超えるデータを処理
- GPUサポート:GPUで変換を高速化
- フレームワーク連携:PyTorch、TensorFlow、HuggingFace
- マルチモーダル:画像、Parquet、CSV、JSON、音声、動画
代わりに次の選択肢を使用してください:
- Pandas:単一マシン上の小規模データ(<1GB)
- Dask:表形式データ、SQLライクな操作
- Spark:エンタープライズETL、SQLクエリ
クイックスタート
インストール
pip install -U 'ray[data]'
データの読み込みと変換
import ray
# Read Parquet files
ds = ray.data.read_parquet("s3://bucket/data/*.parquet")
# Transform data (lazy execution)
ds = ds.map_batches(lambda batch: {"processed": batch["text"].str.lower()})
# Consume data
for batch in ds.iter_batches(batch_size=100):
print(batch)
Ray Trainとの連携
import ray
from ray.train import ScalingConfig
from ray.train.torch import TorchTrainer
# Create dataset
train_ds = ray.data.read_parquet("s3://bucket/train/*.parquet")
def train_func(config):
# Access dataset in training
train_ds = ray.train.get_dataset_shard("train")
for epoch in range(10):
for batch in train_ds.iter_batches(batch_size=32):
# Train on batch
pass
# Train with Ray
trainer = TorchTrainer(
train_func,
datasets={"train": train_ds},
scaling_config=ScalingConfig(num_workers=4, use_gpu=True)
)
trainer.fit()
データの読み込み
クラウドストレージから
import ray
# Parquet (recommended for ML)
ds = ray.data.read_parquet("s3://bucket/data/*.parquet")
# CSV
ds = ray.data.read_csv("s3://bucket/data/*.csv")
# JSON
ds = ray.data.read_json("gs://bucket/data/*.json")
# Images
ds = ray.data.read_images("s3://bucket/images/")
Pythonオブジェクトから
# From list
ds = ray.data.from_items([{"id": i, "value": i * 2} for i in range(1000)])
# From range
ds = ray.data.range(1000000) # Synthetic data
# From pandas
import pandas as pd
df = pd.DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]})
ds = ray.data.from_pandas(df)
変換
バッチのマッピング(ベクトル化)
# Batch transformation (fast)
def process_batch(batch):
batch["doubled"] = batch["value"] * 2
return batch
ds = ds.map_batches(process_batch, batch_size=1000)
行の変換
# Row-by-row (slower)
def process_row(row):
row["squared"] = row["value"] ** 2
return row
ds = ds.map(process_row)
フィルタリング
# Filter rows
ds = ds.filter(lambda row: row["value"] > 100)
グループ化と集計
# Group by column
ds = ds.groupby("category").count()
# Custom aggregation
ds = ds.groupby("category").map_groups(lambda group: {"sum": group["value"].sum()})
GPUで高速化された変換
# Use GPU for preprocessing
def preprocess_images_gpu(batch):
import torch
images = torch.tensor(batch["image"]).cuda()
# GPU preprocessing
processed = images * 255
return {"processed": processed.cpu().numpy()}
ds = ds.map_batches(
preprocess_images_gpu,
batch_size=64,
num_gpus=1 # Request GPU
)
データの書き込み
# Write to Parquet
ds.write_parquet("s3://bucket/output/")
# Write to CSV
ds.write_csv("output/")
# Write to JSON
ds.write_json("output/")
パフォーマンスの最適化
再パーティション化
# Control parallelism
ds = ds.repartition(100) # 100 blocks for 100-core cluster
バッチサイズの調整
# Larger batches = faster vectorized ops
ds.map_batches(process_fn, batch_size=10000) # vs batch_size=100
ストリーミング実行
# Process data larger than memory
ds = ray.data.read_parquet("s3://huge-dataset/")
for batch in ds.iter_batches(batch_size=1000):
process(batch) # Streamed, not loaded to memory
一般的なパターン
バッチ推論
import ray
# Load model
def load_model():
# Load once per worker
return MyModel()
# Inference function
class BatchInference:
def __init__(self):
self.model = load_model()
def __call__(self, batch):
predictions = self.model(batch["input"])
return {"prediction": predictions}
# Run distributed inference
ds = ray.data.read_parquet("s3://data/")
predictions = ds.map_batches(BatchInference, batch_size=32, num_gpus=1)
predictions.write_parquet("s3://output/")
データ前処理パイプライン
# Multi-step pipeline
ds = (
ray.data.read_parquet("s3://raw/")
.map_batches(clean_data)
.map_batches(tokenize)
.map_batches(augment)
.write_parquet("s3://processed/")
)
MLフレームワークとの連携
PyTorch
# Convert to PyTorch
torch_ds = ds.to_torch(label_column="label", batch_size=32)
for batch in torch_ds:
# batch is dict with tensors
inputs, labels = batch["features"], batch["label"]
TensorFlow
# Convert to TensorFlow
tf_ds = ds.to_tf(feature_columns=["image"], label_column="label", batch_size=32)
for features, labels in tf_ds:
# Train model
pass
対応データ形式
| 形式 | 読み込み | 書き込み | 用途 |
|---|---|---|---|
| Parquet | ✅ | ✅ | MLデータ(推奨) |
| CSV | ✅ | ✅ | 表形式データ |
| JSON | ✅ | ✅ | 半構造化データ |
| Images | ✅ | ❌ | コンピュータービジョン |
| NumPy | ✅ | ✅ | 配列 |
| Pandas | ✅ | ❌ | DataFrame |
パフォーマンスのベンチマーク
スケーリング(100GBのデータを処理):
- 1ノード(16コア):約30分
- 4ノード(64コア):約8分
- 16ノード(256コア):約2分
GPUアクセラレーション(画像の前処理):
- CPUのみ:毎秒1,000枚
- GPU 1基:毎秒5,000枚
- GPU 4基:毎秒18,000枚
ユースケース
本番環境へのデプロイ:
- Pinterest:モデルのトレーニング向けラストマイルデータ処理
- ByteDance:マルチモーダルLLMによるオフライン推論のスケーリング
- Spotify:バッチ推論向けMLプラットフォーム
参考資料
リソース
- ドキュメント: https://docs.ray.io/en/latest/data/data.html
- GitHub: https://github.com/ray-project/ray ⭐ 36,000+
- バージョン: Ray 2.40.0+
- サンプル: https://docs.ray.io/en/latest/data/examples/overview.html
コメント
Markdown 対応