Stable Baselines

repository·master·Indexed 43 days ago

https://github.com/stable-baselines-team/stable-baselines

A set of reliable, user-friendly implementations of reinforcement learning algorithms forked from OpenAI Baselines. It supports TensorFlow versions 1.8.0 to 1.14.0 and provides a variety of algorithms including PPO2, DQN, A2C, and SAC with support for Box, Discrete, MultiDiscrete, and MultiBinary action spaces.

Tokens
38.3K
Snippets
92
Records
137
Agent score
55%

What's inside Stable Baselines

  1. Overview of Stable Baselines

    master

    Stable Baselines is a set of improved implementations of Reinforcement Learning (RL) algorithms based on OpenAI Baselines. It provides a unified structure for algorithms, follows PEP8 compliance, and includes documented functions and classes.

    Key features include:

    • Additional algorithms: SAC, TD3, and HER support for DQN, DDPG, SAC, and TD3.
    • Higher code coverage and more tests compared to the original OpenAI Baselines.
    • Integration with the RL Baselines Zoo, which is a collection of over 100 pre-trained agents and provides a simple interface for training, evaluating agents, and hyperparameter tuning.
  2. Explore projects using stable-baselines

    master
    This document lists various external projects, research papers, and implementations that utilize stable-baselines. These range from robotics (Roboy, S-RL Toolbox) and autonomous driving (Donkey Gym, Learning to drive in a day) to game AI (Slime Volleyball, Snake Game AI) and specialized research (Adversarial Policies, Quantized RL).
  3. Use Deep Q Network (DQN)

    master

    DQN implements the Deep Q-Network algorithm and includes extensions like Double-DQN, Dueling-DQN, and Prioritized Experience Replay.

    Important Constraints:

    • Policy Models: DQN does not support stable_baselines.common.policies. You must use its specific policy models (e.g., MlpPolicy, CnnPolicy).
    • Recurrent Policies: Not supported.
    • Multi-processing: Not supported.
    • Gym Spaces:
      • Action Space: Must be Discrete.
      • Observation Space: Supports Discrete and Box.

    Default Extensions:

    • Double-Q learning and Dueling DQN are enabled by default.
    • To disable Dueling DQN, refer to GitHub Issue #406.
    • To disable Double-Q learning, pass the appropriate value to the constructor.
    from stable_baselines import DQN
    from stable_baselines.deepq.policies import MlpPolicy
    import gym
    
    env = gym.make('CartPole-v1')
    model = DQN(MlpPolicy, env, verbose=1)
    model.learn(total_timesteps=25000)
    model.save("deepq_cartpole")
  4. Use Twin Delayed DDPG (TD3)

    master

    TD3 is an actor-critic algorithm that improves upon DDPG using clipped double Q-learning, delayed policy updates, and target policy smoothing.

    Important Constraints:

    • Policies: TD3 does not support stable_baselines.common.policies. It must use its own specific policy models (e.g., MlpPolicy, CnnPolicy) because it requires double Q-value estimation.
    • Action Space: Supports Box (Continuous) and Discrete (though typically used for continuous control). It does not support MultiDiscrete or MultiBinary action spaces.
    • Observation Space: Supports Box, Discrete, MultiDiscrete, and MultiBinary observation spaces.
    • Limitations: Does not support recurrent policies or multi-processing.
    import gym
    from stable_baselines import TD3
    from stable_baselines.td3.policies import MlpPolicy
    from stable_baselines.ddpg.noise import NormalActionNoise
    import numpy as np
    
    env = gym.make('Pendulum-v0')
    n_actions = env.action_space.shape[-1]
    action_noise = NormalActionNoise(mean=np.zeros(n_actions), sigma=0.1 * np.ones(n_actions))
    
    model = TD3(MlpPolicy, env, action_noise=action_noise, verbose=1)
    model.learn(total_timesteps=50000)
    model.save("td3_pendulum")
  5. What is Generative Adversarial Imitation Learning (GAIL)?

    master
    Generative Adversarial Imitation Learning (GAIL) uses expert trajectories to recover a cost function and then learn a policy. It functions similarly to a Generative Adversarial Network (GAN), where a discriminator attempts to distinguish between expert trajectories and trajectories produced by the learned policy (the generator).
  6. Which RL algorithm should I use?

    master

    Algorithm selection depends primarily on your Action Space and whether you need Multiprocessing.

    Discrete Actions

    (Includes Discrete, MultiDiscrete, Binary, and MultiBinary)

    • Single Process: Use DQN (and its extensions like double DQN or prioritized replay) or ACER. DQN is generally more sample efficient due to its replay buffer.
    • Multiprocessed: Use PPO2, A2C, or their successors (ACKTR, ACER).
    • MPI Support: If you can use MPI for multiprocessing, consider PPO1 or TRPO.

    Continuous Actions

    • Single Process: SAC and TD3 are the current State Of The Art (SOTA). Note: Normalization is critical for these algorithms.
    • Multiprocessed: Use PPO2, TRPO, or A2C. If using MPI, you can also choose PPO1 or DDPG.

    Goal Environments

    • If your environment implements the GoalEnv interface, use HER (Hindsight Experience Replay) combined with SAC, TD3, DDPG, or DQN depending on the action space.
  7. How Hindsight Experience Replay (HER) works

    master

    Hindsight Experience Replay (HER) is a method wrapper designed for Off-policy algorithms such as DQN, SAC, TD3, and DDPG. It allows an agent to learn from failed attempts by replaying them as if a different goal had been intended.

    Requirements:

    • The environment must inherit from gym.GoalEnv.
    • To use the .predict() method after loading a model, you must either pass the environment to the .load() method or wrap your environment with HERGoalEnvWrapper.
    from stable_baselines import HER, DQN
    
    # model_class can be DQN, SAC, TD3, or DDPG
    model = HER('MlpPolicy', env, DQN, n_sampled_goal=4, goal_selection_strategy='future')
    model.learn(1000)
  8. Use the PPO1 algorithm

    master

    PPO1 (Proximal Policy Optimization) is an implementation that combines ideas from A2C and TRPO. It uses clipping to ensure the new policy does not deviate too far from the old policy during updates.

    Key Requirements & Differences:

    • MPI Requirement: PPO1 requires OpenMPI. If OpenMPI is not enabled, PPO1 will not be imported into the stable_baselines module.
    • Multiprocessing: Unlike PPO2 (which uses vectorized environments), PPO1 uses MPI for multiprocessing.
    • Recurrent Policies: Not supported (❌).

    Supported Gym Spaces:

    SpaceActionObservation
    Discrete✔️✔️
    Box✔️✔️
    MultiDiscrete✔️✔️
    MultiBinary✔️✔️
    import gym
    from stable_baselines.common.policies import MlpPolicy
    from stable_baselines import PPO1
    
    env = gym.make('CartPole-v1')
    
    model = PPO1(MlpPolicy, env, verbose=1)
    model.learn(total_timesteps=25000)
    model.save("ppo1_cartpole")
    
    # Loading and using the model
    model = PPO1.load("ppo1_cartpole")
    obs = env.reset()
    while True:
        action, _states = model.predict(obs)
        obs, rewards, dones, info = env.step(action)
        env.render()
  9. Soft Actor Critic (SAC) Overview

    master

    SAC is an Off-Policy Maximum Entropy Deep Reinforcement Learning algorithm with a Stochastic Actor. It is the successor to Soft Q-Learning (SQL) and incorporates the double Q-learning trick from TD3. A key feature is that it maximizes a trade-off between expected return and entropy (randomness in the policy).

    Important Constraints:

    • Policy Compatibility: SAC does not support stable_baselines.common.policies because it requires its own specific policy models for double q-values and value estimation. You must use the policies provided in stable_baselines.sac.policies.
    • Recurrent Policies: Not supported. ❌
    • Multi-processing: Not supported. ❌
    • Gym Spaces Support:
      • Action Space: Supports Box. Does not support Discrete or MultiDiscrete.
      • Observation Space: Supports Box, Discrete, MultiDiscrete, and MultiBinary.
  10. Pre-train RL policies using Behavior Cloning

    master

    You can accelerate RL training by using the .pretrain() method to perform Behavior Cloning (BC). This treats imitation learning as a supervised learning problem where the policy network is trained to reproduce expert behavior (observations-actions pairs) from a provided dataset.

    Supported Spaces:

    • Box
    • Discrete

    Important Note on Image Datasets: To avoid memory issues, images from expert demonstrations must be stored in a separate folder rather than directly inside the expert .npz archive. In this case, the obs key in the archive will contain relative paths to the image files.

    model.pretrain(dataset, n_epochs=1000)
  11. Use ACKTR (Actor Critic using Kronecker-Factored Trust Region)

    master

    ACKTR is an algorithm that uses Kronecker-factored approximate curvature (K-FAC) for trust region optimization. It supports recurrent policies and multi-processing.

    Supported Gym Spaces:

    • Discrete: Action (✔️), Observation (✔️)
    • Box: Action (✔️), Observation (✔️)
    • MultiDiscrete: Action (❌), Observation (✔️)
    • MultiBinary: Action (❌), Observation (✔️)
    from stable_baselines import ACKTR
    from stable_baselines.common.policies import MlpPolicy
    
    model = ACKTR(MlpPolicy, env, verbose=1)
    model.learn(total_timesteps=25000)