翻篇收录说明
翻篇网页快照

Diffusion policy pattern — Ray 3.0.0.dev0

https://docs.ray.io/en/master/_collections/train/tutorials/workload-patterns/04d2_policy_learning_pattern.html

最近抓取:2026-12-05 13:05:03(北京时间)

最近内容变化:2026-12-03 00:34:57(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

This notebook builds a mini diffusion-policy pipeline on a real Pendulum-v1 offline dataset and runs it end-to-end on an Anyscale cluster with Ray Train. Learning objectives: How to use Ray Data to...

正文摘录

Diffusion policy pattern# This notebook builds a mini diffusion-policy pipeline on a real Pendulum-v1 offline dataset and runs it end-to-end on an Anyscale cluster with Ray Train. Learning objectives# How to use Ray Data to stream and preprocess Gymnasium rollouts in parallel across CPU workers. How to scale training across multiple A10G GPUs using TorchTrainer with a minimal LightningModule. How to checkpoint every epoch for robust fault tolerance and auto-resume. How to log and visualize metrics using Ray’s built-in results and observability tooling. How to generate actions from a trained policy directly in-notebook, with no need to repackage or redeploy. How to run the full pipeline on Anyscale Workspaces with no infrastructure setup or cluster config required. What problem are you solving? (Inverted Pendulum, Diffusion-Style)# You’re training a policy to swing up and balance an inverted pendulum — a classic control problem. In the Gym Pendulum-v1 environment, the agent sees the current state of the pendulum and must decide what torque to apply at the pivot. What’s a policy?# A policy is a function that maps the current state to an action: \[ \pi_\theta(s_{k}) \;\longrightarrow\; u_{k} \] Here: The state \(s_k\) describes where the pendulum is and how fast it’s moving The action \(u_k\) is the torque you apply to influence future motion The goal is to learn a policy that keeps the pendulum upright by generating the right torque at every step Environment state and action# At each timestep: Symbol Dim Meaning \(\theta_{k}\) scalar Angle of the pendulum \(\dot\theta_{k}\) scalar Angular velocity \(u_{k}\) scalar Torque applied to the base The pendulum starts hanging down and must swing up and maintain balance. Encode the state as: \[ s_{k} = [\cos\theta_{k},\ \sin\theta_{k},\ \dot\theta_{k}] \in \mathbb{R}^3 \] This avoids angle discontinuities (no \(\pm\pi\) jumps) and keeps values in \([-1, 1]\). 1. Dataset tuples# Train on a log of actions from a random policy, then inject artificial noise to simulate the diffusion process: \[ \varepsilon_{k} \sim \mathcal{N}(0, 1), \quad t_{k} \sim \text{Uniform}\{0,\dots,T{-}1\} \] and construct a noisy action: \[ \tilde{u}_k = u_{k} + \varepsilon_{k} \] 2. Training objective# Train a model \(f_\theta\) to predict the injected noise, given the state, the noisy action, and the timestep: \[ \mathcal{L} = \mathbb{E}_{s_{k},\varepsilon_k,t_{k}}\ \big\|f_\theta(s_k, \tilde{u}_k, t_{k}) - \varepsilon_k\big\|_2^2 \] Minimizing this loss teaches the model to de-noise \(\tilde{u}_{k}\) back toward the expert action \(u_k\). 3. Reverse diffusion (sampling)# At inference time, start from noise \(x_T \sim \mathcal{N}(0, 1)\) and de-noise step by step: \[ x_{t} \;\leftarrow\; x_{t} - \eta \cdot f_\theta(s, x_{t}, t), \quad t = T{-}1, \dots, 0 \] After \(T\) steps: \[ x_0 \approx u^\star \] is a valid torque for the current state — a sample from your learned diffusion policy. How to scale this policy learning workload using Ray on Anyscale# This tutorial shows how to take a local PyTorch + Gymnasium workflow and migrate it to a fully distributed, fault-tolerant Ray pipeline running on Anyscale with minimal code changes. Here’s how the transition works: Gym rollouts → Ray Dataset Generate simulation rollouts from Pendulum-v1 and stream them directly into a Ray Dataset, enabling distributed preprocessing (For example, normalization) and automatic partitioning across workers. Local Training → Cluster-scale Distributed Training Wrap a minimal LightningModule in a Ray Train train_loop, then launch training with TorchTrainer across eight A10G GPUs. Ray handles data sharding, worker setup, and device placement without boilerplate. Manual State Saving → Lightning-Integrated Checkpointing & Auto-Resume Checkpointing and metric tracking are handled automatically by PyTorch Lightning and Ray Train V2. The RayTrainReportCallback() forwards Lightning’s checkpoint.ckpt files and logged metrics to Ray, enabling structured, fault-tolerant training with seamless resume support. No manual save or report logic required. Ad-hoc Coordination → Declarative Orchestration Replace manual logging, retry logic, and resource management with Ray-native configs (ScalingConfig, CheckpointConfig, FailureConfig), letting Ray + Anyscale own the orchestration. Notebook-only Inference → Cluster-aware Evaluation After training, perform reverse diffusion sampling in-notebook using the latest checkpoint—but this can easily scale using Ray Data. This flow upgrades a local notebook into a multi-node, resilient training + inference pipeline, using Ray’s native abstractions and running seamlessly inside an Anyscale Workspace, without sacrificing dev agility. 1. Imports and setup# Standard scientific-Python stack, plus Ray for distributed data/training and Lightning for ergonomic model training. # 00. Runtime setup import os import sys import subprocess # Non-secret env var os.environ["RAY_TRAIN_V2_ENABLED"] = "1" # Driver-side install only. !uv pip install -r /home/ray/default/python_depset.lock --system --no-deps --no-cache-dir --index-strategy unsafe-best-match # Propagate dependencies to the Ray cluster. import ray ray.init( runtime_env={ "pip": "/home/ray/default/python_depset.lock", "env_vars": {"RAY_TRAIN_V2_ENABLED": "1"}, }, ignore_reinit_error=True, ) # 01. Imports # Standard Python packages for math, plotting, and data handling import os import shutil import glob import json import uuid import numpy as np import matplotlib.pyplot as plt import pandas as pd import gymnasium as gym # Ray libraries for distributed data and training import ray import ray.data from ray.train.lightning import RayLightningEnvironment from ray.train import ScalingConfig, RunConfig, FailureConfig, CheckpointConfig, get_context, get_checkpoint, report, Checkpoint from ray.train.torch import TorchTrainer # PyTorch Lightning and base PyTorch for model definition and training import lightning.pytorch as pl import torch from torch.utils.data import DataLoader from torch import nn 2. Generate a real pendulum dataset# Roll out a random policy for 10,000 steps, logging: field shape description obs (3,) [cos θ, sin θ, θ̇] noisy_action (1,) ground-truth action + Gaussian noise noise (1,) the injected noise (supervision target) timestep () random diffusion step ∈ [0, 999] You wrap the list of dicts in a Ray Dataset for automatic sharding. # 02. Generate Pendulum offline dataset def make_pendulum_dataset(n_steps: int = 10_000): """ Roll out a random policy in Pendulum-v1 and log (obs, noisy_action, noise, timestep). Returns a Ray Dataset ready for sharding. """ env = gym.make("Pendulum-v1") obs, _ = env.reset(seed=0) data = [] for _ in range(n_steps): action = env.action_space.sample().astype(np.float32) # shape (1,) noise = np.random.randn(*action.shape).astype(np.float32) noisy_action = action + noise # add Gaussian noise timestep = np.random.randint(0, 1000, dtype=np.int64) data.append( { "obs": obs.astype(np.float32), # shape (3,) "noisy_action": noisy_action, # shape (1,) "noise": noise, # shape (1,) "timestep": timestep, } ) # Step environment obs, _, terminated, truncated, _ = env.step(action) if terminated or truncated: obs, _ = env.reset() return ray.data.from_items(data) ds = make_pendulum_dataset(n_steps=int(os.getenv("PENDULUM_STEPS", 10000))) 3. Normalize and split# Pendulum states lie roughly in [–π, π]. Scale to [–1, 1], then shuffle and split 80 / 20 into train and val shards. All transformations execute in parallel across the Ray cluster. # 03. Normalize and split (vector obs ∈ [-π, π]) # Normalize pixel values from [0, 1] to [-1, 1] for training def normalize(batch): # Pendulum observations are roughly in [-π, π] → scale to [-1, 1] batch["obs"] = batch["obs"] / np.pi return batch # Apply normalization in parallel using Ray Data ds = ds.map_batches(normalize, batch_format="numpy") # Count total number of items (triggers actual execution) total = ds.count() print("Total dataset size:", total) # Shuffle and split dataset into 80% training and 20% validation split_idx = int(total * 0.8) ds = ds.random_shuffle() train_ds, val_ds = ds.split_at_indices([split_idx]) print("Train size:", train_ds.count()) print("Val size:", val_ds.count()) 4. DiffusionPolicy LightningModule# A tiny MLP that predicts the injected noise ϵ given: 3D normalized state 1D noisy action scalar timestep (normalized by max_t) It logs per-epoch losses so you can plot later. # 04. DiffusionPolicy for low-dim observation (3D) and action (1D) class DiffusionPolicy(pl.LightningModule): """Tiny MLP that predicts injected noise ϵ given (obs, noisy_action, timestep).""" def __init__(self, obs_dim: int = 3, act_dim: int = 1, max_t: int = 1000): super().__init__() self.max_t = max_t # 3D obs + 1D action + 1 timestep → 1D noise self.net = nn.Sequential( nn.Linear(obs_dim + act_dim + 1, 128), nn.ReLU(), nn.Linear(128, act_dim), ) self.loss_fn = nn.MSELoss() # ---------- forward ---------- def forward(self, obs, noisy_action, timestep): t = timestep.view(-1, 1).float() / self.max_t x = torch.cat([obs, noisy_action, t], dim=1) return self.net(x) # ---------- shared loss ---------- def _shared_step(self, batch): pred = self.forward( batch["obs"].float(), batch["noisy_action"], batch["timestep"], ) return self.loss_fn(pred, batch["noise"]) # ---------- training / validation ---------- def training_step(self, batch, batch_idx): loss = self._shared_step(batch) self.log("train_loss", loss, on_epoch=True, prog_bar=False, sync_dist=True) return loss def validation_step(self, batch, batch_idx): loss = self._shared_step(batch) self.log("val_loss", loss, on_epoch=True, prog_bar=False, sync_dist=True) return loss def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=1e-3) 5. Distributed Train loop with checkpointing# This per-worker function demonstrates: Ray Data to PyTorch: iter_torch_batches() each epoch Lightning-on-Ray: single-GPU trainer per worker Fault tolerance: r