stable-baselines3
Production-ready reinforcement learning algorithms (PPO, SAC, DQN, TD3, DDPG, A2C) with scikit-learn-like API. Use for standard RL experiments, quick prototyping, and well-documented algorithm implementations. Best for single-agent RL with Gymnasium environments. For high-performance parallel training, multi-agent systems, or custom vectorized environments, use pufferlib instead.
Overview
Production-ready reinforcement learning algorithms (PPO, SAC, DQN, TD3, DDPG, A2C) with scikit-learn-like API. Use for standard RL experiments, quick prototyping, and well-documented algorithm implementations. Best for single-agent RL with Gymnasium environments. For high-performance parallel training, multi-agent systems, or custom vectorized environments, use pufferlib instead.
Source: https://github.com/DenDen047/claude-scientific-skills · MIT LICENSE · © 2025 K-Dense Inc.
System prompt
The instruction block that defines the agent's role, rules and output format.
# Stable Baselines3
## Overview
Stable Baselines3 (SB3) is a PyTorch-based library providing reliable implementations of reinforcement learning algorithms. This skill provides comprehensive guidance for training RL agents, creating custom environments, implementing callbacks, and optimizing training workflows using SB3's unified API.
## Core Capabilities
### 1. Training RL Agents
**Basic Training Pattern:**
```python
import gymnasium as gym
from stable_baselines3 import PPO
# Create environment
env = gym.make("CartPole-v1")
# Initialize agent
model = PPO("MlpPolicy", env, verbose=1)
# Train the agent
model.learn(total_timesteps=10000)
# Save the model
model.save("ppo_cartpole")
# Load the model (without prior instantiation)
model = PPO.load("ppo_cartpole", env=env)
```
**Important Notes:**
- `total_timesteps` is a lower bound; actual training may exceed this due to batch collection
- Use `model.load()` as a static method, not on an existing instance
- The replay buffer is NOT saved with the model to save space
**Algorithm Selection:**
Use `references/algorithms.md` for detailed algorithm characteristics and selection guidance. Quick reference:
- **PPO/A2C**: General-purpose, supports all action space types, good for multiprocessing
- **SAC/TD3**: Continuous control, off-policy, sample-efficient
- **DQN**: Discrete actions, off-policy
- **HER**: Goal-conditioned tasks
See `scripts/train_rl_agent.py` for a complete training template with best practices.
### 2. Custom Environments
**Requirements:**
Custom environments must inherit from `gymnasium.Env` and implement:
- `__init__()`: Define action_space and observation_space
- `reset(seed, options)`: Return initial observation and info dict
- `step(action)`: Return observation, reward, terminated, truncated, info
- `render()`: Visualization (optional)
- `close()`: Cleanup resources
**Key Constraints:**
- Image observations must be `np.uint8` in range [0, 255]
- Use channel-first format when possible (channels, height, width)
- SB3 normalizes images automatically by dividing by 255
- Set `normalize_images=False` in policy_kwargs if pre-normalized
- SB3 does NOT support `Discrete` or `MultiDiscrete` spaces with `start!=0`
**Validation:**
```python
from stable_baselines3.common.env_checker import check_env
check_env(env, warn=True)
```
See `scripts/custom_env_template.py` for a complete custom environment template and `references/custom_environments.md` for comprehensive guidance.
### 3. Vectorized Environments
**Purpose:**
Vectorized environments run multiple environment instances in parallel, accelerating training and enabling certain wrappers (frame-stacking, normalization).
**Types:**
- **DummyVecEnv**: Sequential execution on current process (for lightweight environments)
- **SubprocVecEnv**: Parallel execution across processes (for compute-heavy environments)
**Quick Setup:**
```python
from stable_baselines3.common.env_util import make_vec_env
# Create 4 parallel environments
env = make_vec_env("CartPole-v1", n_envs=4, vec_env_cls=SubprocVecEnv)
model = PPO("MlpPolicy", env, verbose=1)
model.learn(total_timesteps=25000)
```
**Off-Policy Optimization:**
When using multiple environments with off-policy algorithms (SAC, TD3, DQN), set `gradient_steps=-1` to perform one gradient update per environment step, balancing wall-clock time and sample efficiency.
**API Differences:**
- `reset()` returns only observations (info available in `vec_env.reset_infos`)
- `step()` returns 4-tuple: `(obs, rewards, dones, infos)` not 5-tuple
- Environments auto-reset after episodes
- Terminal observations available via `infos[env_idx]["terminal_observation"]`
See `references/vectorized_envs.md` for detailed information on wrappers and advanced usage.
### 4. Callbacks for Monitoring and Control
**Purpose:**
Callbacks enable monitoring metrics, saving checkpoints, implementing early stopping, and custom training logic without modifying core algorithms.
**Common Callbacks:**
- **EvalCallback**: Evaluate periodically and save best model
- **CheckpointCallback**: Save model checkpoints at intervals
- **StopTrainingOnRewardThreshold**: Stop when target reward reached
- **ProgressBarCallback**: Display training progress with timing
**Custom Callback Structure:**
```python
from stable_baselines3.common.callbacks import BaseCallback
class CustomCallback(BaseCallback):
def _on_training_start(self):
# Called before first rollout
pass
def _on_step(self):
# Called after each environment step
# Return False to stop training
return True
def _on_rollout_end(self):
# Called at end of rollout
pass
```
**Available Attributes:**
- `self.model`: The RL algorithm instance
- `self.num_timesteps`: Total environment steps
- `self.training_env`: The training environment
**Chaining Callbacks:**
```python
from stable_baselines3.common.callbacks import CallbackList
callback = CallbackList([eval_callback, checkpoint_callback, custom_callback])
model.learn(total_timesteps=10000, callback=callback)
```
See `references/callbacks.md` for comprehensive callback documentation.
### 5. Model Persistence and Inspection
**Saving and Loading:**
```python
# Save model
model.save("model_name")
# Save normalization statistics (if using VecNormalize)
vec_env.save("vec_normalize.pkl")
# Load model
model = PPO.load("model_name", env=env)
# Load normalization statistics
vec_env = VecNormalize.load("vec_normalize.pkl", vec_env)
```
**Parameter Access:**
```python
# Get parameters
params = model.get_parameters()
# Set parameters
model.set_parameters(params)
# Access PyTorch state dict
state_dict = model.policy.state_dict()
```
### 6. Evaluation and Recording
**Evaluation:**
```python
from stable_baselines3.common.evaluation import evaluate_policy
mean_reward, std_reward = evaluate_policy(
model,
env,
n_eval_episodes=10,
deterministic=True
)
```
**Video Recording:**
```python
from stable_baselines3.common.vec_env import VecVideoRecorder
# Wrap environment with video recorder
env = VecVideoRecorder(
env,
"videos/",
record_video_trigger=lambda x: x % 2000 == 0,
video_length=200
)
```
See `scripts/evaluate_agent.py` for a complete evaluation and recording template.
### 7. Advanced Features
**Learning Rate Schedules:**
```python
def linear_schedule(initial_value):
def func(progress_remaining):
# progress_remaining goes from 1 to 0
return progress_remaining * initial_value
return func
model = PPO("MlpPolicy", env, learning_rate=linear_schedule(0.001))
```
**Multi-Input Policies (Dict Observations):**
```python
model = PPO("MultiInputPolicy", env, verbose=1)
```
Use when observations are dictionaries (e.g., combining images with sensor data).
**Hindsight Experience Replay:**
```python
from stable_baselines3 import SAC, HerReplayBuffer
model = SAC(
"MultiInputPolicy",
env,
replay_buffer_class=HerReplayBuffer,
replay_buffer_kwargs=dict(
n_sampled_goal=4,
goal_selection_strategy="future",
),
)
```
**TensorBoard Integration:**
```python
model = PPO("MlpPolicy", env, tensorboard_log="./tensorboard/")
model.learn(total_timesteps=10000)
```
## Workflow Guidance
**Starting a New RL Project:**
1. **Define the problem**: Identify observation space, action space, and reward structure
2. **Choose algorithm**: Use `references/algorithms.md` for selection guidance
3. **Create/adapt environment**: Use `scripts/custom_env_template.py` if needed
4. **Validate environment**: Always run `check_env()` before training
5. **Set up training**: Use `scripts/train_rl_agent.py` as starting template
6. **Add monitoring**: Implement callbacks for evaluation and checkpointing
7. **Optimize performance**: Consider vectorized environments for speed
8. **Evaluate and iterate**: Use `scripts/evaluate_agent.py` for assessment
**Common Issues:**
- **Memory errors**: Reduce `buffer_size` for off-policy algorithms or use fewer parallel environments
- **Slow training**: Consider SubprocVecEnv for parallel environments
- **Unstable training**: Try different algorithms, tune hyperparameters, or check reward scaling
- **Import errors**: Ensure `stable_baselines3` is installed: `uv pip install stable-baselines3[extra]`
## Resources
### scripts/
- `train_rl_agent.py`: Complete training script template with best practices
- `evaluate_agent.py`: Agent evaluation and video recording template
- `custom_env_template.py`: Custom Gym environment template
### references/
- `algorithms.md`: Detailed algorithm comparison and selection guide
- `custom_environments.md`: Comprehensive custom environment creation guide
- `callbacks.md`: Complete callback system reference
- `vectorized_envs.md`: Vectorized environment usage and wrappers
## Installation
```bash
# Basic installation
uv pip install stable-baselines3
# With extra dependencies (Tensorboard, etc.)
uv pip install stable-baselines3[extra]
``` User prompt template
Fill in the variables and send it to run the skill: {{variables}}
Variables
| Name | Required | Description | Example |
|---|
Full skill configuration
The standard .aiskill file in JSON and YAML.
{
"format": "aiskill/v1",
"skill": {
"name": "stable-baselines3",
"slug": "stable-baselines3",
"version": "1.0.0",
"description": "Production-ready reinforcement learning algorithms (PPO, SAC, DQN, TD3, DDPG, A2C) with scikit-learn-like API. Use for standard RL experiments, quick prototyping, and well-documented algorithm implementations. Best for single-agent RL with Gymnasium environments. For high-performance parallel training, multi-agent systems, or custom vectorized environments, use pufferlib instead.",
"category": "Research",
"tags": [
"research-science",
"agents",
"api",
"performance"
],
"platforms": [
"chatgpt",
"claude-code",
"cursor"
],
"tested_environment": "Agent Skills convention (SKILL.md) — works with Claude Code, Cursor, ChatGPT/Codex and compatible agents",
"license": "MIT LICENSE"
},
"prompts": {
"system": "# Stable Baselines3\r\n\r\n## Overview\r\n\r\nStable Baselines3 (SB3) is a PyTorch-based library providing reliable implementations of reinforcement learning algorithms. This skill provides comprehensive guidance for training RL agents, creating custom environments, implementing callbacks, and optimizing training workflows using SB3's unified API.\r\n\r\n## Core Capabilities\r\n\r\n### 1. Training RL Agents\r\n\r\n**Basic Training Pattern:**\r\n\r\n```python\r\nimport gymnasium as gym\r\nfrom stable_baselines3 import PPO\r\n\r\n# Create environment\r\nenv = gym.make(\"CartPole-v1\")\r\n\r\n# Initialize agent\r\nmodel = PPO(\"MlpPolicy\", env, verbose=1)\r\n\r\n# Train the agent\r\nmodel.learn(total_timesteps=10000)\r\n\r\n# Save the model\r\nmodel.save(\"ppo_cartpole\")\r\n\r\n# Load the model (without prior instantiation)\r\nmodel = PPO.load(\"ppo_cartpole\", env=env)\r\n```\r\n\r\n**Important Notes:**\r\n- `total_timesteps` is a lower bound; actual training may exceed this due to batch collection\r\n- Use `model.load()` as a static method, not on an existing instance\r\n- The replay buffer is NOT saved with the model to save space\r\n\r\n**Algorithm Selection:**\r\nUse `references/algorithms.md` for detailed algorithm characteristics and selection guidance. Quick reference:\r\n- **PPO/A2C**: General-purpose, supports all action space types, good for multiprocessing\r\n- **SAC/TD3**: Continuous control, off-policy, sample-efficient\r\n- **DQN**: Discrete actions, off-policy\r\n- **HER**: Goal-conditioned tasks\r\n\r\nSee `scripts/train_rl_agent.py` for a complete training template with best practices.\r\n\r\n### 2. Custom Environments\r\n\r\n**Requirements:**\r\nCustom environments must inherit from `gymnasium.Env` and implement:\r\n- `__init__()`: Define action_space and observation_space\r\n- `reset(seed, options)`: Return initial observation and info dict\r\n- `step(action)`: Return observation, reward, terminated, truncated, info\r\n- `render()`: Visualization (optional)\r\n- `close()`: Cleanup resources\r\n\r\n**Key Constraints:**\r\n- Image observations must be `np.uint8` in range [0, 255]\r\n- Use channel-first format when possible (channels, height, width)\r\n- SB3 normalizes images automatically by dividing by 255\r\n- Set `normalize_images=False` in policy_kwargs if pre-normalized\r\n- SB3 does NOT support `Discrete` or `MultiDiscrete` spaces with `start!=0`\r\n\r\n**Validation:**\r\n```python\r\nfrom stable_baselines3.common.env_checker import check_env\r\n\r\ncheck_env(env, warn=True)\r\n```\r\n\r\nSee `scripts/custom_env_template.py` for a complete custom environment template and `references/custom_environments.md` for comprehensive guidance.\r\n\r\n### 3. Vectorized Environments\r\n\r\n**Purpose:**\r\nVectorized environments run multiple environment instances in parallel, accelerating training and enabling certain wrappers (frame-stacking, normalization).\r\n\r\n**Types:**\r\n- **DummyVecEnv**: Sequential execution on current process (for lightweight environments)\r\n- **SubprocVecEnv**: Parallel execution across processes (for compute-heavy environments)\r\n\r\n**Quick Setup:**\r\n```python\r\nfrom stable_baselines3.common.env_util import make_vec_env\r\n\r\n# Create 4 parallel environments\r\nenv = make_vec_env(\"CartPole-v1\", n_envs=4, vec_env_cls=SubprocVecEnv)\r\n\r\nmodel = PPO(\"MlpPolicy\", env, verbose=1)\r\nmodel.learn(total_timesteps=25000)\r\n```\r\n\r\n**Off-Policy Optimization:**\r\nWhen using multiple environments with off-policy algorithms (SAC, TD3, DQN), set `gradient_steps=-1` to perform one gradient update per environment step, balancing wall-clock time and sample efficiency.\r\n\r\n**API Differences:**\r\n- `reset()` returns only observations (info available in `vec_env.reset_infos`)\r\n- `step()` returns 4-tuple: `(obs, rewards, dones, infos)` not 5-tuple\r\n- Environments auto-reset after episodes\r\n- Terminal observations available via `infos[env_idx][\"terminal_observation\"]`\r\n\r\nSee `references/vectorized_envs.md` for detailed information on wrappers and advanced usage.\r\n\r\n### 4. Callbacks for Monitoring and Control\r\n\r\n**Purpose:**\r\nCallbacks enable monitoring metrics, saving checkpoints, implementing early stopping, and custom training logic without modifying core algorithms.\r\n\r\n**Common Callbacks:**\r\n- **EvalCallback**: Evaluate periodically and save best model\r\n- **CheckpointCallback**: Save model checkpoints at intervals\r\n- **StopTrainingOnRewardThreshold**: Stop when target reward reached\r\n- **ProgressBarCallback**: Display training progress with timing\r\n\r\n**Custom Callback Structure:**\r\n```python\r\nfrom stable_baselines3.common.callbacks import BaseCallback\r\n\r\nclass CustomCallback(BaseCallback):\r\n def _on_training_start(self):\r\n # Called before first rollout\r\n pass\r\n\r\n def _on_step(self):\r\n # Called after each environment step\r\n # Return False to stop training\r\n return True\r\n\r\n def _on_rollout_end(self):\r\n # Called at end of rollout\r\n pass\r\n```\r\n\r\n**Available Attributes:**\r\n- `self.model`: The RL algorithm instance\r\n- `self.num_timesteps`: Total environment steps\r\n- `self.training_env`: The training environment\r\n\r\n**Chaining Callbacks:**\r\n```python\r\nfrom stable_baselines3.common.callbacks import CallbackList\r\n\r\ncallback = CallbackList([eval_callback, checkpoint_callback, custom_callback])\r\nmodel.learn(total_timesteps=10000, callback=callback)\r\n```\r\n\r\nSee `references/callbacks.md` for comprehensive callback documentation.\r\n\r\n### 5. Model Persistence and Inspection\r\n\r\n**Saving and Loading:**\r\n```python\r\n# Save model\r\nmodel.save(\"model_name\")\r\n\r\n# Save normalization statistics (if using VecNormalize)\r\nvec_env.save(\"vec_normalize.pkl\")\r\n\r\n# Load model\r\nmodel = PPO.load(\"model_name\", env=env)\r\n\r\n# Load normalization statistics\r\nvec_env = VecNormalize.load(\"vec_normalize.pkl\", vec_env)\r\n```\r\n\r\n**Parameter Access:**\r\n```python\r\n# Get parameters\r\nparams = model.get_parameters()\r\n\r\n# Set parameters\r\nmodel.set_parameters(params)\r\n\r\n# Access PyTorch state dict\r\nstate_dict = model.policy.state_dict()\r\n```\r\n\r\n### 6. Evaluation and Recording\r\n\r\n**Evaluation:**\r\n```python\r\nfrom stable_baselines3.common.evaluation import evaluate_policy\r\n\r\nmean_reward, std_reward = evaluate_policy(\r\n model,\r\n env,\r\n n_eval_episodes=10,\r\n deterministic=True\r\n)\r\n```\r\n\r\n**Video Recording:**\r\n```python\r\nfrom stable_baselines3.common.vec_env import VecVideoRecorder\r\n\r\n# Wrap environment with video recorder\r\nenv = VecVideoRecorder(\r\n env,\r\n \"videos/\",\r\n record_video_trigger=lambda x: x % 2000 == 0,\r\n video_length=200\r\n)\r\n```\r\n\r\nSee `scripts/evaluate_agent.py` for a complete evaluation and recording template.\r\n\r\n### 7. Advanced Features\r\n\r\n**Learning Rate Schedules:**\r\n```python\r\ndef linear_schedule(initial_value):\r\n def func(progress_remaining):\r\n # progress_remaining goes from 1 to 0\r\n return progress_remaining * initial_value\r\n return func\r\n\r\nmodel = PPO(\"MlpPolicy\", env, learning_rate=linear_schedule(0.001))\r\n```\r\n\r\n**Multi-Input Policies (Dict Observations):**\r\n```python\r\nmodel = PPO(\"MultiInputPolicy\", env, verbose=1)\r\n```\r\nUse when observations are dictionaries (e.g., combining images with sensor data).\r\n\r\n**Hindsight Experience Replay:**\r\n```python\r\nfrom stable_baselines3 import SAC, HerReplayBuffer\r\n\r\nmodel = SAC(\r\n \"MultiInputPolicy\",\r\n env,\r\n replay_buffer_class=HerReplayBuffer,\r\n replay_buffer_kwargs=dict(\r\n n_sampled_goal=4,\r\n goal_selection_strategy=\"future\",\r\n ),\r\n)\r\n```\r\n\r\n**TensorBoard Integration:**\r\n```python\r\nmodel = PPO(\"MlpPolicy\", env, tensorboard_log=\"./tensorboard/\")\r\nmodel.learn(total_timesteps=10000)\r\n```\r\n\r\n## Workflow Guidance\r\n\r\n**Starting a New RL Project:**\r\n\r\n1. **Define the problem**: Identify observation space, action space, and reward structure\r\n2. **Choose algorithm**: Use `references/algorithms.md` for selection guidance\r\n3. **Create/adapt environment**: Use `scripts/custom_env_template.py` if needed\r\n4. **Validate environment**: Always run `check_env()` before training\r\n5. **Set up training**: Use `scripts/train_rl_agent.py` as starting template\r\n6. **Add monitoring**: Implement callbacks for evaluation and checkpointing\r\n7. **Optimize performance**: Consider vectorized environments for speed\r\n8. **Evaluate and iterate**: Use `scripts/evaluate_agent.py` for assessment\r\n\r\n**Common Issues:**\r\n\r\n- **Memory errors**: Reduce `buffer_size` for off-policy algorithms or use fewer parallel environments\r\n- **Slow training**: Consider SubprocVecEnv for parallel environments\r\n- **Unstable training**: Try different algorithms, tune hyperparameters, or check reward scaling\r\n- **Import errors**: Ensure `stable_baselines3` is installed: `uv pip install stable-baselines3[extra]`\r\n\r\n## Resources\r\n\r\n### scripts/\r\n- `train_rl_agent.py`: Complete training script template with best practices\r\n- `evaluate_agent.py`: Agent evaluation and video recording template\r\n- `custom_env_template.py`: Custom Gym environment template\r\n\r\n### references/\r\n- `algorithms.md`: Detailed algorithm comparison and selection guide\r\n- `custom_environments.md`: Comprehensive custom environment creation guide\r\n- `callbacks.md`: Complete callback system reference\r\n- `vectorized_envs.md`: Vectorized environment usage and wrappers\r\n\r\n## Installation\r\n\r\n```bash\r\n# Basic installation\r\nuv pip install stable-baselines3\r\n\r\n# With extra dependencies (Tensorboard, etc.)\r\nuv pip install stable-baselines3[extra]\r\n```",
"user_template": ""
},
"variables": [],
"install": {
"steps": [
{
"title": "Download & unzip",
"detail": "Download the .zip package from SkillVault and unzip it. The stable-baselines3/ folder contains SKILL.md plus any companion scripts, references and assets."
},
{
"title": "Copy into your agent skills directory",
"detail": "Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code), .codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or reload the session."
},
{
"title": "Use it",
"detail": "Describe the task in natural language; the agent loads the skill automatically when the request matches the skill description."
}
]
},
"usage": {
"steps": []
},
"metadata": {
"author": "SkillVault",
"source": "https://skillvault.top/skills/stable-baselines3",
"exported_at": "2026-11-03T07:41:38.702Z"
}
} format: aiskill/v1
skill:
name: stable-baselines3
slug: stable-baselines3
version: 1.0.0
description: >-
Production-ready reinforcement learning algorithms (PPO, SAC, DQN, TD3, DDPG, A2C) with
scikit-learn-like API. Use for standard RL experiments, quick prototyping, and well-documented
algorithm implementations. Best for single-agent RL with Gymnasium environments. For
high-performance parallel training, multi-agent systems, or custom vectorized environments, use
pufferlib instead.
category: Research
tags:
- research-science
- agents
- api
- performance
platforms:
- chatgpt
- claude-code
- cursor
tested_environment: >-
Agent Skills convention (SKILL.md) — works with Claude Code, Cursor, ChatGPT/Codex and
compatible agents
license: MIT LICENSE
prompts:
system: "# Stable Baselines3\r\n\r\n## Overview\r\n\r\nStable Baselines3 (SB3) is a PyTorch-based library providing reliable implementations of reinforcement learning algorithms. This skill provides comprehensive guidance for training RL agents, creating custom environments, implementing callbacks, and optimizing training workflows using SB3's unified API.\r\n\r\n## Core Capabilities\r\n\r\n### 1. Training RL Agents\r\n\r\n**Basic Training Pattern:**\r\n\r\n```python\r\nimport gymnasium as gym\r\nfrom stable_baselines3 import PPO\r\n\r\n# Create environment\r\nenv = gym.make(\"CartPole-v1\")\r\n\r\n# Initialize agent\r\nmodel = PPO(\"MlpPolicy\", env, verbose=1)\r\n\r\n# Train the agent\r\nmodel.learn(total_timesteps=10000)\r\n\r\n# Save the model\r\nmodel.save(\"ppo_cartpole\")\r\n\r\n# Load the model (without prior instantiation)\r\nmodel = PPO.load(\"ppo_cartpole\", env=env)\r\n```\r\n\r\n**Important Notes:**\r\n- `total_timesteps` is a lower bound; actual training may exceed this due to batch collection\r\n- Use `model.load()` as a static method, not on an existing instance\r\n- The replay buffer is NOT saved with the model to save space\r\n\r\n**Algorithm Selection:**\r\nUse `references/algorithms.md` for detailed algorithm characteristics and selection guidance. Quick reference:\r\n- **PPO/A2C**: General-purpose, supports all action space types, good for multiprocessing\r\n- **SAC/TD3**: Continuous control, off-policy, sample-efficient\r\n- **DQN**: Discrete actions, off-policy\r\n- **HER**: Goal-conditioned tasks\r\n\r\nSee `scripts/train_rl_agent.py` for a complete training template with best practices.\r\n\r\n### 2. Custom Environments\r\n\r\n**Requirements:**\r\nCustom environments must inherit from `gymnasium.Env` and implement:\r\n- `__init__()`: Define action_space and observation_space\r\n- `reset(seed, options)`: Return initial observation and info dict\r\n- `step(action)`: Return observation, reward, terminated, truncated, info\r\n- `render()`: Visualization (optional)\r\n- `close()`: Cleanup resources\r\n\r\n**Key Constraints:**\r\n- Image observations must be `np.uint8` in range [0, 255]\r\n- Use channel-first format when possible (channels, height, width)\r\n- SB3 normalizes images automatically by dividing by 255\r\n- Set `normalize_images=False` in policy_kwargs if pre-normalized\r\n- SB3 does NOT support `Discrete` or `MultiDiscrete` spaces with `start!=0`\r\n\r\n**Validation:**\r\n```python\r\nfrom stable_baselines3.common.env_checker import check_env\r\n\r\ncheck_env(env, warn=True)\r\n```\r\n\r\nSee `scripts/custom_env_template.py` for a complete custom environment template and `references/custom_environments.md` for comprehensive guidance.\r\n\r\n### 3. Vectorized Environments\r\n\r\n**Purpose:**\r\nVectorized environments run multiple environment instances in parallel, accelerating training and enabling certain wrappers (frame-stacking, normalization).\r\n\r\n**Types:**\r\n- **DummyVecEnv**: Sequential execution on current process (for lightweight environments)\r\n- **SubprocVecEnv**: Parallel execution across processes (for compute-heavy environments)\r\n\r\n**Quick Setup:**\r\n```python\r\nfrom stable_baselines3.common.env_util import make_vec_env\r\n\r\n# Create 4 parallel environments\r\nenv = make_vec_env(\"CartPole-v1\", n_envs=4, vec_env_cls=SubprocVecEnv)\r\n\r\nmodel = PPO(\"MlpPolicy\", env, verbose=1)\r\nmodel.learn(total_timesteps=25000)\r\n```\r\n\r\n**Off-Policy Optimization:**\r\nWhen using multiple environments with off-policy algorithms (SAC, TD3, DQN), set `gradient_steps=-1` to perform one gradient update per environment step, balancing wall-clock time and sample efficiency.\r\n\r\n**API Differences:**\r\n- `reset()` returns only observations (info available in `vec_env.reset_infos`)\r\n- `step()` returns 4-tuple: `(obs, rewards, dones, infos)` not 5-tuple\r\n- Environments auto-reset after episodes\r\n- Terminal observations available via `infos[env_idx][\"terminal_observation\"]`\r\n\r\nSee `references/vectorized_envs.md` for detailed information on wrappers and advanced usage.\r\n\r\n### 4. Callbacks for Monitoring and Control\r\n\r\n**Purpose:**\r\nCallbacks enable monitoring metrics, saving checkpoints, implementing early stopping, and custom training logic without modifying core algorithms.\r\n\r\n**Common Callbacks:**\r\n- **EvalCallback**: Evaluate periodically and save best model\r\n- **CheckpointCallback**: Save model checkpoints at intervals\r\n- **StopTrainingOnRewardThreshold**: Stop when target reward reached\r\n- **ProgressBarCallback**: Display training progress with timing\r\n\r\n**Custom Callback Structure:**\r\n```python\r\nfrom stable_baselines3.common.callbacks import BaseCallback\r\n\r\nclass CustomCallback(BaseCallback):\r\n def _on_training_start(self):\r\n # Called before first rollout\r\n pass\r\n\r\n def _on_step(self):\r\n # Called after each environment step\r\n # Return False to stop training\r\n return True\r\n\r\n def _on_rollout_end(self):\r\n # Called at end of rollout\r\n pass\r\n```\r\n\r\n**Available Attributes:**\r\n- `self.model`: The RL algorithm instance\r\n- `self.num_timesteps`: Total environment steps\r\n- `self.training_env`: The training environment\r\n\r\n**Chaining Callbacks:**\r\n```python\r\nfrom stable_baselines3.common.callbacks import CallbackList\r\n\r\ncallback = CallbackList([eval_callback, checkpoint_callback, custom_callback])\r\nmodel.learn(total_timesteps=10000, callback=callback)\r\n```\r\n\r\nSee `references/callbacks.md` for comprehensive callback documentation.\r\n\r\n### 5. Model Persistence and Inspection\r\n\r\n**Saving and Loading:**\r\n```python\r\n# Save model\r\nmodel.save(\"model_name\")\r\n\r\n# Save normalization statistics (if using VecNormalize)\r\nvec_env.save(\"vec_normalize.pkl\")\r\n\r\n# Load model\r\nmodel = PPO.load(\"model_name\", env=env)\r\n\r\n# Load normalization statistics\r\nvec_env = VecNormalize.load(\"vec_normalize.pkl\", vec_env)\r\n```\r\n\r\n**Parameter Access:**\r\n```python\r\n# Get parameters\r\nparams = model.get_parameters()\r\n\r\n# Set parameters\r\nmodel.set_parameters(params)\r\n\r\n# Access PyTorch state dict\r\nstate_dict = model.policy.state_dict()\r\n```\r\n\r\n### 6. Evaluation and Recording\r\n\r\n**Evaluation:**\r\n```python\r\nfrom stable_baselines3.common.evaluation import evaluate_policy\r\n\r\nmean_reward, std_reward = evaluate_policy(\r\n model,\r\n env,\r\n n_eval_episodes=10,\r\n deterministic=True\r\n)\r\n```\r\n\r\n**Video Recording:**\r\n```python\r\nfrom stable_baselines3.common.vec_env import VecVideoRecorder\r\n\r\n# Wrap environment with video recorder\r\nenv = VecVideoRecorder(\r\n env,\r\n \"videos/\",\r\n record_video_trigger=lambda x: x % 2000 == 0,\r\n video_length=200\r\n)\r\n```\r\n\r\nSee `scripts/evaluate_agent.py` for a complete evaluation and recording template.\r\n\r\n### 7. Advanced Features\r\n\r\n**Learning Rate Schedules:**\r\n```python\r\ndef linear_schedule(initial_value):\r\n def func(progress_remaining):\r\n # progress_remaining goes from 1 to 0\r\n return progress_remaining * initial_value\r\n return func\r\n\r\nmodel = PPO(\"MlpPolicy\", env, learning_rate=linear_schedule(0.001))\r\n```\r\n\r\n**Multi-Input Policies (Dict Observations):**\r\n```python\r\nmodel = PPO(\"MultiInputPolicy\", env, verbose=1)\r\n```\r\nUse when observations are dictionaries (e.g., combining images with sensor data).\r\n\r\n**Hindsight Experience Replay:**\r\n```python\r\nfrom stable_baselines3 import SAC, HerReplayBuffer\r\n\r\nmodel = SAC(\r\n \"MultiInputPolicy\",\r\n env,\r\n replay_buffer_class=HerReplayBuffer,\r\n replay_buffer_kwargs=dict(\r\n n_sampled_goal=4,\r\n goal_selection_strategy=\"future\",\r\n ),\r\n)\r\n```\r\n\r\n**TensorBoard Integration:**\r\n```python\r\nmodel = PPO(\"MlpPolicy\", env, tensorboard_log=\"./tensorboard/\")\r\nmodel.learn(total_timesteps=10000)\r\n```\r\n\r\n## Workflow Guidance\r\n\r\n**Starting a New RL Project:**\r\n\r\n1. **Define the problem**: Identify observation space, action space, and reward structure\r\n2. **Choose algorithm**: Use `references/algorithms.md` for selection guidance\r\n3. **Create/adapt environment**: Use `scripts/custom_env_template.py` if needed\r\n4. **Validate environment**: Always run `check_env()` before training\r\n5. **Set up training**: Use `scripts/train_rl_agent.py` as starting template\r\n6. **Add monitoring**: Implement callbacks for evaluation and checkpointing\r\n7. **Optimize performance**: Consider vectorized environments for speed\r\n8. **Evaluate and iterate**: Use `scripts/evaluate_agent.py` for assessment\r\n\r\n**Common Issues:**\r\n\r\n- **Memory errors**: Reduce `buffer_size` for off-policy algorithms or use fewer parallel environments\r\n- **Slow training**: Consider SubprocVecEnv for parallel environments\r\n- **Unstable training**: Try different algorithms, tune hyperparameters, or check reward scaling\r\n- **Import errors**: Ensure `stable_baselines3` is installed: `uv pip install stable-baselines3[extra]`\r\n\r\n## Resources\r\n\r\n### scripts/\r\n- `train_rl_agent.py`: Complete training script template with best practices\r\n- `evaluate_agent.py`: Agent evaluation and video recording template\r\n- `custom_env_template.py`: Custom Gym environment template\r\n\r\n### references/\r\n- `algorithms.md`: Detailed algorithm comparison and selection guide\r\n- `custom_environments.md`: Comprehensive custom environment creation guide\r\n- `callbacks.md`: Complete callback system reference\r\n- `vectorized_envs.md`: Vectorized environment usage and wrappers\r\n\r\n## Installation\r\n\r\n```bash\r\n# Basic installation\r\nuv pip install stable-baselines3\r\n\r\n# With extra dependencies (Tensorboard, etc.)\r\nuv pip install stable-baselines3[extra]\r\n```"
user_template: ""
variables: []
install:
steps:
- title: Download & unzip
detail: >-
Download the .zip package from SkillVault and unzip it. The stable-baselines3/ folder
contains SKILL.md plus any companion scripts, references and assets.
- title: Copy into your agent skills directory
detail: >-
Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code),
.codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or
reload the session.
- title: Use it
detail: >-
Describe the task in natural language; the agent loads the skill automatically when the
request matches the skill description.
usage:
steps: []
metadata:
author: SkillVault
source: https://skillvault.top/skills/stable-baselines3
exported_at: "2026-11-03T07:41:38.702Z"
Installation guide
- 1
Download & unzip
Download the .zip package from SkillVault and unzip it. The stable-baselines3/ folder contains SKILL.md plus any companion scripts, references and assets.
- 2
Copy into your agent skills directory
Move the folder into your agent's skills directory — e.g. ~/.claude/skills/ (Claude Code), .codex/skills/, .cursor/skills/ or your project's .claude/skills/ folder — then restart or reload the session.
- 3
Use it
Describe the task in natural language; the agent loads the skill automatically when the request matches the skill description.
How to use
Platform compatibility
ChatGPT GPTs
OpenAI
Paste the system prompt into the GPT "Instructions" field and keep the user template as your starter message.
Official docsClaude Code
Anthropic
Save the exported .aiskill JSON as a skill file in your project or paste the system prompt into CLAUDE.md / a slash-command markdown file.
Official docsCursor
Anysphere
Copy the system prompt into .cursor/rules/*.mdc (or Project Rules in Settings) and reference the user template in your agent prompts.
Official docsRelated skills
database-lookup
Search 78 public scientific, biomedical, materials science, and economic databases via their REST APIs and return structured JSON results. Covers physics/astronomy (NASA, NIST, SDSS, SIMBAD, Exoplanet Archive), earth/environment (USGS, NOAA, EPA, OpenWeatherMap), chemistry/drugs (PubChem, ChEMBL, DrugBank, FDA, KEGG, DailyMed, ZINC, BindingDB), materials science (Materials Project, COD), biology/genomics (Reactome, BRENDA, UniProt, STRING, Ensembl, NCBI Gene, GEO, GTEx, PDB, AlphaFold, InterPro, ChEBI, BioGRID, Gene Ontology, QuickGO, NCBI Protein/Taxonomy, dbSNP, SRA, ENA, gnomAD, UCSC Genome, ENCODE, JASPAR, MouseMine, PRIDE, LINCS L1000, Human Protein Atlas, Human Cell Atlas, RummaGEO, Metabolomics Workbench, EMDB, Addgene), disease/clinical (COSMIC, Open Targets, ClinPGx, ClinicalTrials.gov, OMIM, ClinVar, GDC/TCGA, cBioPortal, DisGeNET, GWAS Catalog, Monarch, HPO), regulatory (FDA, USPTO, SEC EDGAR), economics/finance (FRED, BEA, BLS, Federal Reserve, World Bank, ECB, US Treasury, Alpha Vantage, Data Commons), and demographics (US Census, Eurostat, WHO). Use this skill whenever the user wants to look up compounds, drugs, proteins, genes, pathways, enzymes, gene expression, variants, clinical trials, patents, SEC filings, economic indicators, crystal structures, astronomical objects, earthquakes, weather, or any data from a public database API. Also trigger when the user mentions any database by name or asks about molecular properties, drug-target interactions, binding affinities, protein interactions, pathway membership, pharmacogenomics, economic time series, materials properties, commercially available compounds, virtual screening, compound purchasability, chemical libraries, building blocks, cancer genomics, somatic mutations, tumor mutation profiles, nucleotide sequences, genome assemblies, sequencing reads, ENA accessions, INSDC data, or wants to cross-reference entities across sources.
perplexity-search
Perform AI-powered web searches with real-time information using Perplexity models via LiteLLM and OpenRouter. This skill should be used when conducting web searches for current information, finding recent scientific literature, getting grounded answers with source citations, or accessing information beyond the model knowledge cutoff. Provides access to multiple Perplexity models including Sonar Pro, Sonar Pro Search (advanced agentic search), and Sonar Reasoning Pro through a single OpenRouter API key.
pufferlib
High-performance reinforcement learning framework optimized for speed and scale. Use when you need fast parallel training, vectorized environments, multi-agent systems, or integration with game environments (Atari, Procgen, NetHack). Achieves 2-10x speedups over standard implementations. For quick prototyping or standard algorithm implementations with extensive documentation, use stable-baselines3 instead.