
Stable-Baselines3: Saving and Loading Trained Agents
Save a Stable-Baselines3 agent with model.save(), reload it with the matching algorithm’s load(), and run it with predict(). For example, PPO.load("ppo_cartpole.zip") restores a saved PPO model - but not its environment or wrapper state.
A working reload also needs:
- A compatible environment, with matching observation and action spaces.
- Separate normalization statistics if training used
VecNormalize, plus a replay buffer for off-policy training when stored experience is needed. - The correct rollout API: Gymnasium’s
step()returns 5 values; SB3’s VecEnv returns 4. - Trusted files and recorded dependency versions to help prevent loading and compatibility problems.
This guide covers saving, loading, device selection, and testing one complete episode, plus fixes for common errors.
Stable-Baselines3: Save, Load, and Test an Agent
Saving and Loading Models - Stable Baselines 3 Tutorial (P.2)
sbb-itb-61a6e59
2. Save the Agent with model.save()
Create CartPole-v1, train a PPO agent, and save it with model.save(). This writes ppo_cartpole.zip to the current directory. Then close the environment and delete the model before moving on.
from pathlib import Path import gymnasium as gym from stable_baselines3 import PPO env = gym.make("CartPole-v1") model = PPO("MlpPolicy", env, verbose=1) model.learn(total_timesteps=10_000) model.save("ppo_cartpole") print(Path("ppo_cartpole.zip").resolve()) env.close() del model
Check the Saved ZIP Contents
The official save-format documentation describes the archive’s serialized algorithm data and PyTorch state. You can inspect its filenames without extracting anything:
from zipfile import ZipFile with ZipFile("ppo_cartpole.zip") as archive: print("\n".join(archive.namelist()))
Typical entries include data, policy.pth, and policy.optimizer.pth.
The ZIP doesn’t store everything needed to resume training. Here’s what it saves and what you need to handle separately:
| Artifact | Preserved by model.save() |
Additional action | Loading significance |
|---|---|---|---|
| Algorithm data and hyperparameters | Yes | Use the matching algorithm class | Restores saved model configuration |
| Policy parameters and optimizer state | Yes | None for a standard save | Supports inference and continued training |
| Observation and action spaces | Yes | Recreate a compatible environment | Allows environment compatibility checks |
VecNormalize statistics |
No | Save and load them separately | Preserves observation and reward normalization |
| Off-policy replay buffer | No | Use save_replay_buffer() and load_replay_buffer() |
Preserves stored experience for continued training |
| Environment runtime state and custom code | No | Retain code and settings separately | Required to recreate the environment and preprocessing |
Save External State Separately
Save runtime state outside the ZIP. Keep environment and preprocessing settings alongside it, plus any custom environment and wrapper code.
If training uses VecNormalize, save its statistics with the wrapper’s save() method. Restore them with VecNormalize.load().
For off-policy training, save experience with model.save_replay_buffer("replay_buffer.pkl") and restore it with model.load_replay_buffer("replay_buffer.pkl").
3. Load with the Matching Algorithm Class
Reload the saved archive using the matching algorithm class. load() returns a new model instance, so assign the result to a variable.
from stable_baselines3 import PPO model = PPO.load("ppo_cartpole.zip")
Attach an Environment and Choose a Device
Pass env=env to continue training or use the model in a specific environment. During loading, SB3 checks that the saved observation and action spaces match those of the supplied environment.
import gymnasium as gym env = gym.make("CartPole-v1") model = PPO.load("ppo_cartpole.zip", env=env, device="cpu")
The device parameter puts the loaded model on the CPU or another supported device. It only changes where the model runs.
Once loaded, the model can run predict() in a compatible Gymnasium environment.
4. Run and Test the Loaded Agent
Run predict() with Gymnasium
Use the loaded model and the recreated env from the previous section. Set deterministic=True and run one episode.
episode_return = 0.0 try: obs, info = env.reset(seed=42) while True: action, _ = model.predict(obs, deterministic=True) obs, reward, terminated, truncated, info = env.step(action) episode_return += float(reward) if terminated or truncated: break print(f"Episode return: {episode_return:.1f}") finally: env.close()
Use the SB3 VecEnv path below ONLY when the agent runs inside a vectorized environment.
Run Agents with the SB3 VecEnv API
SB3's vectorized environments use a different interface: observations are batched, and step() returns four values rather than Gymnasium's five.
from stable_baselines3.common.vec_env import DummyVecEnv import gymnasium as gym vec_env = DummyVecEnv([lambda: gym.make("CartPole-v1")]) try: obs = vec_env.reset() episode_return = 0.0 while True: actions, _ = model.predict(obs, deterministic=True) obs, rewards, dones, infos = vec_env.step(actions) episode_return += float(rewards[0]) if dones[0]: print(f"Episode return: {episode_return:.1f}") break finally: vec_env.close()
Fix Loading and Execution Errors
If the rollout fails, check the API signature first.
- If
model.predict()produces a shape or unpacking error, pass onlyobs, not the(obs, info)tuple returned by Gymnasium'senv.reset(). - If the agent runs but the observation shape or data type is wrong, compare your environment setup with the one used during training.
- When switching between Gymnasium and
VecEnv, match thereset()andstep()signatures to the API you're using. - If the rollout finishes but the return is low, the policy may be undertrained. A low return doesn't always mean loading failed.
5. Conclusion: Save and Load Checklist
Use this checklist to check your save, load, and rollout steps. The ZIP contains only model parameters and hyperparameters. Wrappers and replay buffers remain outside it.
Save VecNormalize stats separately. To continue training, save the replay buffer separately, too. Recreate the environment and its wrappers before using the agent - loading does not restore wrapper state.
Before using the agent, confirm:
- Artifact files are trusted and unmodified.
- Exact dependency versions are recorded.
- Observation and action spaces match those used during training.
- Preprocessing is restored, including normalization stats.
predict()completes one full episode using the correct Gymnasium or SB3 VecEnv API.
FAQs
How do I resume training without resetting the timestep count?
The provided search results don’t explain how to resume training in Stable-Baselines3 or preserve the timestep count, so I can’t verify the method from those results. Share the relevant article section or save/load excerpt, and I can give you an exact answer.
How can I verify a loaded agent matches its original performance?
Backtest the loaded agent on historical data to recreate its original environment conditions. Compare the results using the same statistical metrics used during initial training.
To monitor model drift, compare feature, label, and prediction distributions with those in the training data. Use statistical tests such as the Kolmogorov-Smirnov (KS) test to check for distribution changes. Large drops in F1 or AUC indicate a decline in the agent’s predictive performance.
Can I load an agent with a different Stable-Baselines3 version?
The provided search results don’t address Stable-Baselines3 version compatibility, so they don’t confirm whether you can load an agent saved with a different version.