Stable baselines3

From FOURTEEN1416/academic-agent-toolkit · View interactive version

Stable baselines3 is an AI agent skill from the GitHub repository FOURTEEN1416/academic-agent-toolkit. 强化学习标准实现:PPO/SAC/DQN/TD3/DDPG/A2C,scikit-learn 风格 API。用于智能决策策略学习与仿真环境内的策略训练(仿真赛事 C 赛道)。

How to use this skill

Skill file

<!--ACAT-ADAPTED: 收编自 K-Dense-AI/scientific-agent-skills@36d8f13a1e754618794bf42f417884940077b4ae(MIT,fork FOURTEEN1416)。上游兼容性声明与网络/凭据类依赖在本仓库不适用,执行以本机实装版本为准;溯源见 references/UPSTREAM.md。2026-10-16 仿真建模赛补齐批。2026-11-16 重收编:融入上游 v2.72.0(2d2065f)增量——SB3 2.9.0/PyTorch>=2.8 重审、示例补 device/seed 与 env.close() 卫生、VecNormalize 保存/加载配对与续训口径、评估环境分离与_episode 统计口径、自定义环境模板观测 (4,) 变更、gradient_steps=-1 语义、HER 前置条件与有界 demo 免责;上游文末引用节未收编。-->

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.

Current upstream: SB3 2.9.0 (June 15, 2026). Docs: stable-baselines3.readthedocs.io.

Installation

Tested against stable-baselines3 2.9.0. Requires Python 3.10+ (3.9 dropped in 2.8.0) and PyTorch >= 2.8.

# Basic installation
uv pip install "stable-baselines3==2.9.0"

# With extra dependencies (TensorBoard, ale-py for Atari, etc.)
uv pip install "stable-baselines3[extra]==2.9.0"

The 2.9.0 release supports Gymnasium >=0.29.1,<2.0; this review exercised

Gymnasium 1.3.0, PyTorch 2.14.1 and Python 3.13 on CPU. pandas/matplotlib

are now optional extras. Installation requires network unless packages are cached;

local RL training needs no credentials or service endpoints.

On zsh, quote brackets: uv pip install 'stable-baselines3[extra]==2.9.0'.

For MuJoCo continuous-control benchmarks:

uv pip install "gymnasium[mujoco]"

Check your version:

import stable_baselines3
print(stable_baselines3.__version__)

Related Projects

Core Capabilities

1. Training RL Agents

Basic Training Pattern:

import 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, device="cpu", seed=0)

# 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, device="cpu")
env.close()

Important Notes:

Algorithm 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.

2. Custom Environments

Requirements:

Custom environments must inherit from gymnasium.Env and implement:

Key Constraints:

Validation:

from stable_baselines3.common.env_checker import check_env

check_env(env, warn=True)

See the template and environment guide.

The template now observes both agent and random goal coordinates, shape (4,);

old shape (2,) checkpoints require retraining. gym.make("CustomEnv-v0") adds

the 100-step time limit; direct CustomEnv() does not. check_env checks API

consistency, not Markov sufficiency, reward correctness or learnability.

3. Vectorized Environments

Purpose:

Vectorized environments run multiple environment instances in parallel, accelerating training and enabling certain wrappers (frame-stacking, normalization).

Types:

Quick Setup:

from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env

# DummyVecEnv batches 4 lightweight environments sequentially.
env = make_vec_env("CartPole-v1", n_envs=4, seed=0)
try:
    model = PPO("MlpPolicy", env, verbose=1, device="cpu")
    model.learn(total_timesteps=25000)
finally:
    env.close()

Off-Policy Optimization:

With step-based train_freq, gradient_steps=-1 matches gradient updates to

collected transitions (train_freq * n_envs) after warmup. This changes compute

and reuse of data; benchmark it rather than assuming it is always faster.

SubprocVecEnv creation belongs under a main guard in a Python file.

API Differences:

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:

Custom Callback Structure:

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:

Chaining Callbacks:

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:

from stable_baselines3.common.vec_env import VecNormalize

# After training with VecNormalize, save a matching pair:
model.save("model_name")
model.get_vec_normalize_env().save("vec_normalize.pkl")

# Build the same underlying environment and wrappers before loading:
vec_env = make_vec_env("Pendulum-v1", n_envs=1, seed=20000)
vec_env = VecNormalize.load("vec_normalize.pkl", vec_env)
vec_env.training = False
vec_env.norm_reward = False
model = PPO.load("model_name", env=vec_env, device="cpu")

This is a continuation fragment for a PPO/Pendulum run with normalization.

Load only trusted model/statistics files. For off-policy training continuation,

save_replay_buffer() / load_replay_buffer() are separate from save() / load().

Resume with a live environment and learn(..., reset_num_timesteps=False).

Parameter Access:

# 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:

When training uses VecNormalize, load its saved training statistics into a separate evaluation environment with the same observation wrappers. Set training=False to freeze those statistics and norm_reward=False to report rewards in the original units; do not fit normalization on evaluation episodes. Save the normalization state alongside the model checkpoint.

from stable_baselines3.common.evaluation import evaluate_policy

mean_reward, std_reward = evaluate_policy(
    model,
    eval_env,  # Separate Monitor-wrapped environment with held-out seeds
    n_eval_episodes=10,
    deterministic=True
)

Video Recording:

from stable_baselines3.common.vec_env import VecVideoRecorder

# Requires moviepy, an FFmpeg encoder and the environment rendering dependency.
env = make_vec_env("CartPole-v1", n_envs=1, env_kwargs={"render_mode": "rgb_array"})
# Wrap before stepping, and close after recording to flush the clip.
env = VecVideoRecorder(
    env,
    "videos/",
    record_video_trigger=lambda x: x % 2000 == 0,
    video_length=200
)

Use evaluate_agent.py, passing algorithm=SAC etc.

for the training algorithm and the normalization file from that exact checkpoint.

The helper records one bounded clip. It raises on a missing requested statistics

file. MaskablePPO requires the specialized contrib evaluator.

Evaluate whole episodes on a separate Monitor-wrapped environment. Report the

number of episodes, seeds, reward units, wrapper stack and deterministic/stochastic

action choice. Episode SD is not a confidence interval across training runs. Use

multiple independently trained seeds and a final held-out test after checkpoint

selection; a short smoke run proves mechanics, not a good policy.

7. Advanced Features

Learning Rate Schedules:

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):

model = PPO("MultiInputPolicy", env, verbose=1)

Use when observations are dictionaries (e.g., combining images with sensor data).

Hindsight Experience Replay (illustrative; requires a goal environment):

from stable_baselines3 import SAC, HerReplayBuffer

# env must expose observation/achieved_goal/desired_goal and vectorized compute_reward.
model = SAC(
    "MultiInputPolicy",
    env,
    replay_buffer_class=HerReplayBuffer,
    replay_buffer_kwargs=dict(
        n_sampled_goal=4,
        goal_selection_strategy="future",
    ),
)

TensorBoard Integration:

model = PPO("MlpPolicy", env, tensorboard_log="./tensorboard/")
model.learn(total_timesteps=10000)

The scripts and bounded CPU fixtures are executed in the repository suite. Long

training budgets, HER/CNN/Atari/MuJoCo and unexecuted reference fragments are

illustrative; retain the task-specific wrappers and validation described there.

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:

Resources

scripts/

references/

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.