Install any skill in seconds. Free to start, no credit card required.
Get Started Free →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.
| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 65% | 0% |
| case-02 | ✗→✓ | ▲ Improved | 52% | 0% |
| case-06 | ✗→✓ | ▲ Improved | 106% | 0% |
| case-03 | ✓→✓ | = Same ✓ | 119% | 0% |
| case-04 | ✓→✓ | = Same ✓ | 62% | 0% |
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.
Current upstream: SB3 2.8.0 (April 2026). Docs: stable-baselines3.readthedocs.io.
Tested against stable-baselines3 2.8.0. Requires Python 3.10+ (3.9 dropped in 2.8.0) and PyTorch >= 2.3.
bash# Basic installation uv pip install "stable-baselines3>=2.8" # With extra dependencies (TensorBoard, ale-py for Atari, etc.) uv pip install "stable-baselines3[extra]>=2.8"
On zsh, quote brackets: uv pip install 'stable-baselines3[extra]>=2.8'.
For MuJoCo continuous-control benchmarks:
bashuv pip install "gymnasium[mujoco]"
Check your version:
pythonimport stable_baselines3 print(stable_baselines3.__version__)
sb3-contrib packageBasic Training Pattern:
pythonimport gymnasium as gym from stable_baselines3 import PPO # Create environment env = gym.make("CartPole-v1") # Initialize agent (device="cpu" is often faster for MlpPolicy on small envs) 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 collectionmodel.load() as a static method, not on an existing instanceAlgorithm Selection: Use references/algorithms.md for detailed algorithm characteristics and selection guidance. Quick reference:
See scripts/train_rl_agent.py for a complete training template with best practices.
Requirements: Custom environments must inherit from gymnasium.Env and implement:
__init__(): Define action_space and observation_spacereset(seed, options): Return initial observation and info dictstep(action): Return observation, reward, terminated, truncated, inforender(): Visualization (optional)close(): Cleanup resourcesKey Constraints:
np.uint8 in range 0, 255]normalize_images=False in policy_kwargs if pre-normalizedDiscrete or MultiDiscrete spaces with start!=0Validation:
pythonfrom 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.
Purpose: Vectorized environments run multiple environment instances in parallel, accelerating training and enabling certain wrappers (frame-stacking, normalization).
Types:
Quick Setup:
pythonfrom 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-tupleinfos[env_idx]["terminal_observation"]See references/vectorized_envs.md for detailed information on wrappers and advanced usage.
Purpose: Callbacks enable monitoring metrics, saving checkpoints, implementing early stopping, and custom training logic without modifying core algorithms.
Common Callbacks:
Custom Callback Structure:
pythonfrom 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 instanceself.num_timesteps: Total environment stepsself.training_env: The training environmentChaining Callbacks:
pythonfrom 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.
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()
Evaluation:
pythonfrom stable_baselines3.common.evaluation import evaluate_policy mean_reward, std_reward = evaluate_policy( model, env, n_eval_episodes=10, deterministic=True )
Video Recording:
pythonfrom 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.
Learning Rate Schedules:
pythondef 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):
pythonmodel = PPO("MultiInputPolicy", env, verbose=1)
Use when observations are dictionaries (e.g., combining images with sensor data).
Hindsight Experience Replay:
pythonfrom 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:
pythonmodel = PPO("MlpPolicy", env, tensorboard_log="./tensorboard/") model.learn(total_timesteps=10000)
Starting a New RL Project:
references/algorithms.md for selection guidancescripts/custom_env_template.py if neededcheck_env() before trainingscripts/train_rl_agent.py as starting templatescripts/evaluate_agent.py for assessmentCommon Issues:
buffer_size for off-policy algorithms or use fewer parallel environmentsstable_baselines3 is installed: uv pip install 'stable-baselines3[extra]>=2.8'train_rl_agent.py: Complete training script template with best practicesevaluate_agent.py: Agent evaluation and video recording templatecustom_env_template.py: Custom Gym environment templatealgorithms.md: Detailed algorithm comparison and selection guidecustom_environments.md: Comprehensive custom environment creation guidecallbacks.md: Complete callback system referencevectorized_envs.md: Vectorized environment usage and wrappersOther measured skills in the registry, with their headline benchmark lift.